【问题标题】:Inputting values into an existing table within MS Word将值输入到 MS Word 中的现有表中
【发布时间】:2014-07-03 19:41:55
【问题描述】:

我的程序的目的是制作一个模板 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"; 可能没有与我设置其余代码的方式正确集成,所以任何帮助都会得到帮助

【问题讨论】:

    标签: c# ms-word


    【解决方案1】:

    一些观察:

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

    另一件事。

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

    【讨论】:

    • 我承认应该保存更改,但一定忘记更改了。感谢您的帮助,我已根据您的反馈进行了一些更改,现在似乎一切正常。
    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多