2014-07-02 14 views
0

我的程序的目的是製作一個模板Word文檔的副本,其中包含一個表格,並將文本數據輸入到所述表格的單元格中。我的問題是,無論什麼時候我運行該程序,它都不會輸入任何文本到單元格中,我已經在線搜索,並且據我所知,如何將文本輸入到單元格中應該沒有任何問題。將值輸入MS 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」;可能不與我建立了我的代碼,所以任何幫助將appriciated

回答

0

的一些觀察,其餘的方式妥善整合:

  • 如果您關閉指定wdDoNotSaveChanges,你不會在保存的文檔中參見 「測試」。如果正在顯示打開的文檔 (您可能需要使窗口和應用程序可見以檢查 ),您應該在關閉之前立即在打開的文檔 中看到它。
  • 當您使用。新增添加到文獻集,Word將治療 文件(在這種情況下testDoc2.docx爲模板,和 willcreate另一個新文件,將需要 之前被命名爲您保存到磁盤。因此,即使是被保存的更改,他們將 不會對testDoc2.docx。如果你想打開一個文檔並 解決它,而不是使用。新增

另一件事。開。

當您打開「模板」並將其保存爲新文檔時,您已經真的擁有需要使用的文檔和應用程序對象,即除非您需要關閉並退出現有應用程序。因爲某些原因。

+0

我承認應該保存這些改變,但一定忘記改變它。感謝您的幫助,我根據您的反饋進行了一些更改,現在情況似乎正常。 – user3799505