There is a code which from the DataTable and form fields creates a Word document based on a specific template. But for some reason, after pressing the save button again, the error "object link does not indicate an object instance" crashes on the line of code:
document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); Some variables had to be declared globally, since for some reason they were not recognized in the try - catch , if declared locally. Full function code:
DataTable dt_fasad = new DataTable(); Word._Document document; Word._Application application = new Word.Application(); Object trueObj = true; Object falseObj = false; object missingObj = Missing.Value; object templatePathObj; private void button2_Click(object sender, EventArgs e) { //открытие файла try { string documentpath = Application.StartupPath.ToString() + "\\act.docx"; missingObj = Missing.Value; templatePathObj = documentpath; document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); //заполнение закладок object bookmarkObj_fio = "z1"; object bookmarkObj_fioCopy = "z3"; object bookmarkObj_unp = "z2"; object bookmarkObj_adres = "z4"; object bookmarkObj_rs = "z6"; object bookmarkObj_sum = "z7"; object bookmarkObj_data = "zData"; Word.Range bookmarkRange_fio = document.Bookmarks.get_Item(ref bookmarkObj_fio).Range; Word.Range bookmarkRange_fioCopy = document.Bookmarks.get_Item(ref bookmarkObj_fioCopy).Range; Word.Range bookmarkRange_unp = document.Bookmarks.get_Item(ref bookmarkObj_unp).Range; Word.Range bookmarkRange_adres = document.Bookmarks.get_Item(ref bookmarkObj_adres).Range; Word.Range bookmarkRange_rs = document.Bookmarks.get_Item(ref bookmarkObj_rs).Range; Word.Range bookmarkRange_sum = document.Bookmarks.get_Item(ref bookmarkObj_sum).Range; Word.Range bookmarkRange_data = document.Bookmarks.get_Item(ref bookmarkObj_data).Range; //Указываем содержимое закладок bookmarkRange_fio.Text = textBox2.Text; bookmarkRange_unp.Text = textBox3.Text; bookmarkRange_fioCopy.Text = textBox2.Text; bookmarkRange_fioCopy.Bold = 1; bookmarkRange_adres.Text = textBox5.Text; bookmarkRange_rs.Text = textBox4.Text; bookmarkRange_data.Text = DateTime.Today.ToString("dd.MM.yyyy"); double summ = 0; //Получаем проведенные работы var dtres = dt_fasad.AsEnumerable() .GroupBy(t => new { Id = t.Field<int>("Картридж") }) .Select(g => new { g.Key.Id, Value = String.Join(", ", g.Select(i => i.Field<string>("Проведенные_работы"))) }).ToList(); var sumres = dt_fasad.AsEnumerable() .GroupBy(t => new { Id = t.Field<int>("Картридж") }) .Select(g => new { g.Key.Id, Value = g.Sum(s => (s.Field<double>("Общая_цена"))) }).ToList(); var res2 = from r in dt_fasad.AsEnumerable() group r by r["Марка"] into g select new { p = g.Key }; //работа с таблицей int ik = 2; int ir = 2; Word.Table _table = document.Tables[1]; //Выбрать уже существующую таблицу внутри документа можно по ее порядковому номеру (начиная с 1 и начала документа) _table.AllowAutoFit = true; foreach (var zap in dtres) { _table.Rows.Add(ref missingObj); Word.Range _currentRange = _table.Cell(ik, 3).Range; Word.Range _currentRangeNumb = _table.Cell(ik, 1).Range; Word.Range _currentRangeId = _table.Cell(ik, 2).Range; _currentRange.Text = zap.Value.ToString(); _currentRangeNumb.Text = Convert.ToString(ik - 1); _currentRangeId.Text = zap.Id.ToString(); _table.Rows[ik].SetHeight(35, Word.WdRowHeightRule.wdRowHeightAuto); ik++; } foreach (var sumchik in sumres) { Word.Range _currentRangeCena = _table.Cell(ir, 4).Range; Word.Range _currentRangeCenaNoNDS = _table.Cell(ir, 5).Range; Word.Range _currentRangeNDS = _table.Cell(ir, 6).Range; Word.Range _currentRangeSummaNDS = _table.Cell(ir, 7).Range; Word.Range _currentRangeCenaNDS = _table.Cell(ir, 8).Range; _currentRangeCena.Text = Math.Round(sumchik.Value, 2).ToString(); _currentRangeCenaNoNDS.Text = Math.Round(sumchik.Value, 2).ToString(); summ += Math.Round(sumchik.Value, 2); _currentRangeNDS.Text = "Без НДС"; _currentRangeSummaNDS.Text = "-"; _currentRangeCenaNDS.Text = Math.Round(sumchik.Value, 2).ToString(); ir++; } _table.Rows.Add(ref missingObj); _table.Rows[ik].Height = 15; _table.Columns[1].SetWidth(25, Word.WdRulerStyle.wdAdjustProportional); _table.Columns[2].SetWidth(40, Word.WdRulerStyle.wdAdjustProportional); _table.Columns[3].SetWidth(200, Word.WdRulerStyle.wdAdjustProportional); _table.Columns[4].SetWidth(30, Word.WdRulerStyle.wdAdjustProportional); _table.Columns[5].SetWidth(55, Word.WdRulerStyle.wdAdjustProportional); _table.Rows[ik].Cells[2].Merge(_table.Rows[ik].Cells[3]); Word.Range _currentObsh = _table.Cell(ik, 2).Range; Word.Range _currentCenaObs = _table.Cell(ik, 3).Range; Word.Range _currentCenaNoNDS = _table.Cell(ik, 4).Range; Word.Range _currentNDSProc = _table.Cell(ik, 5).Range; Word.Range _currentSumNDS = _table.Cell(ik, 6).Range; Word.Range _currentSOBSHSUm = _table.Cell(ik, 7).Range; _currentObsh.Text = "Итого"; _currentObsh.Bold = 1; _currentCenaObs.Text = Math.Round(summ, 2).ToString(); _currentCenaNoNDS.Text = Math.Round(summ, 2).ToString(); _currentNDSProc.Text = "x"; _currentSumNDS.Text = "-"; _currentSOBSHSUm.Text = Math.Round(summ, 2).ToString(); //регистрируем новую валюту - белорусский рубль (BYN) RusCurrency.Register("BYN", true, "белорусский рубль", "белорусских рубля", "белорусских рублей", "копейка", "копейки", "копеек"); //С числом работаем bookmarkRange_sum.Text = RusCurrency.Str(summ, "BYN"); bookmarkRange_sum.Bold = 1; // //Вывод на печать //document.PrintOut(ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.FileName = "act_na_pechat"; saveFileDialog1.DefaultExt = ".docx"; saveFileDialog1.Filter = "Word Documents|*.docx"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { document.SaveAs(saveFileDialog1.FileName, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj); } document.Close(Word.WdSaveOptions.wdDoNotSaveChanges); application.Quit(); document = null; application = null; } catch (Exception ex) { MessageBox.Show("Текст ошибки: "+ ex.Message); document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; } } Tell me, please, where I could make a mistake. The first time I work with word and by code it should be clear that I picked up a little bit of everything where possible)