我的程序的目的是制作一个模板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 =“测试”; 可能没有正确整合我设置其余代码的方式所以任何帮助都会得到满足
答案 0 :(得分:0)
一些观察结果:
另一件事。
当您打开“模板”并将其另存为新文档时,您已经拥有了需要使用的文档和应用程序对象,即除非您需要关闭并退出现有应用程序。出于某种原因。