C# 将值输入到MS Word中的现有表中

C# 将值输入到MS Word中的现有表中,c#,ms-word,C#,Ms Word,我的程序的目的是复制一个模板Word文档,其中包含一个表,并将文本数据输入到所述表的单元格中。我的问题是,每当我运行程序时,它都不会向单元格中输入任何文本,我已经在线搜索了,据我所知,将文本输入单元格的方式应该不会有任何问题 这是相关代码 try { //create filepaths for template and the soon to be created file object oMissing = System.Reflection.Missing.Value; obj

我的程序的目的是复制一个模板Word文档,其中包含一个表,并将文本数据输入到所述表的单元格中。我的问题是,每当我运行程序时,它都不会向单元格中输入任何文本,我已经在线搜索了,据我所知,将文本输入单元格的方式应该不会有任何问题

这是相关代码

try
{
  //create filepaths for template and the soon to be created file
  object oMissing = System.Reflection.Missing.Value;
  object notReadOnly = false;
  object oldDocPath = (object)@"Desktop:\testDoc.docx";
  object newDocPath = (object)@"Desktop:\testDoc2.docx";

  //start up word doc
  Word.Application app = new Word.Application();

  //open template in word
  Word.Document oldDoc = app.Documents.Open(ref oldDocPath, 
  ref oMissing, ref notReadOnly, ref oMissing, ref oMissing, ref oMissing,
  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

  //save template under new name to make a copy
  app.ActiveDocument.SaveAs2(ref newDocPath, 
  ref oMissing, ref notReadOnly, ref oMissing, ref oMissing, ref oMissing,
  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

  //close template and open the new document
  object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
  ((_Document)oldDoc).Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
  Marshal.FinalReleaseComObject(oldDoc);
  ((_Application)app).Quit(ref oMissing, ref oMissing, ref oMissing);
  Marshal.FinalReleaseComObject(app);
  Word._Application oWord;
  Word._Document oDoc;
  oWord = new Word.Application();
  oDoc = oWord.Documents.Add(ref newDocPath, ref oMissing, ref oMissing, ref oMissing);

  //populate the table
  Word.Table tbl = oDoc.Tables[1];
  tbl.Cell(1,1).Range.Text = "Test";

  //Close the last Word doc
  ((_Document)oDoc).Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
  Marshal.FinalReleaseComObject(oDoc);
  ((_Application)oWord).Quit(ref oMissing, ref oMissing, ref oMissing);
  Marshal.FinalReleaseComObject(oWord);
}
catch( Exception ex )
{
  MessageBox.Show("Exception Caught: " + ex.Message);
}
好,;我最好的猜测是tbl.Cell(1,1).Range.Text=“Test”可能没有与我设置代码其余部分的方式正确集成,因此任何帮助都会受到重视

一些观察结果:

  • 如果在关闭时指定wdDoNotSaveChanges,则不会看到 保存文档中的“测试”。您应该在打开的文档中看到它 在关闭之前,如果正在显示打开的文档 (您可能需要使窗口和应用程序可见以进行检查 那)
  • 使用.Add添加到文档集合时,Word将 文档(在本例中为testDoc2.docx作为模板,以及 将创建另一个需要在之前命名的新文档 您可以将其保存到磁盘。因此,即使正在保存更改,它们也会 不适用于testDoc2.docx。如果要打开文档并使用 它,使用.Open代替.Add
还有一件事


当你打开你的“模板”并将其另存为新文档,您已经拥有了需要使用的文档和应用程序对象,也就是说,除非您需要关闭并退出现有应用程序。出于某种原因。

无可否认,我本来应该保存更改,但一定忘了更改。感谢您的帮助,我根据您的反馈进行了一些更改现在一切似乎都很顺利。