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

时间:2014-07-02 22:47:29

标签: c# ms-word

我的程序的目的是制作一个模板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 =“测试”; 可能没有正确整合我设置其余代码的方式所以任何帮助都会得到满足

1 个答案:

答案 0 :(得分:0)

一些观察结果:

  • 如果在关闭时指定wdDoNotSaveChanges,则无法看到 保存文档中的“测试”。您应该在打开的文档中看到它 如果正在显示打开的文档,请在关闭之前立即关闭 (您可能需要使窗口和应用程序可见以进行检查 这一点)。
  • 当您使用.Add添加到文档集合时,Word将会处理 文档(在本例中为testDoc2.docx作为模板,和 将创建另一个需要先命名的新文档 你把它保存到磁盘。因此,即使改变得以保存,他们也会 不是testDoc2.docx。如果要打开文档并继续操作 它,使用.Open而不是.Add

另一件事。

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