2016-07-07 50 views
0

我需要你的幫助,在word文檔的特定區域插入文本。如何將文本插入到現有Word文檔C#中的確切位置?

我有一個從.txt文件插入到Word文檔的文本,但我需要它被放置在一個確切的區域不只是在任何地方。

我的代碼:

 string[] readText = File.ReadAllLines(@"p:\CARTAP1.txt"); 

     foreach (string s in readText) 
     { 
      Console.WriteLine(s); 
     } 


     Application application = new Application(); 
     Document document = application.Documents.Open(@"P:\PreciboCancelado.doc"); 
     application.Visible = true; 
     application.Selection.TypeText(readText[2]); 
+3

[如何使用C#插入字符到文件(HTTP的可能重複://計算器.com/questions/98484/how-to-insert-characters-to-a-file-using-c-sharp) – meJustAndrew

+1

你必須閱讀漏洞文檔並重新寫入,並添加新文本。有人問這[這裏](http://stackoverflow.com/questions/98484/how-to-insert-characters-to-a-file-using-c-sharp),並得到了類似的答案。 – meJustAndrew

+1

我對Word文檔不太熟悉,但如果是我,我會利用Intellisence和/或[調試器](http://www.codeproject.com/Articles/79508/Mastering-Debugging -in-Visual-Studio-A-Beginn),並查看在「文檔」中找到的屬性和方法。您可能要編輯「Document」對象並保存它,覆蓋現有文件。 –

回答

0

您可以在Word中的書籤嘗試。也許這個鏈接可以幫助你http://gregmaxey.mvps.org/word_tip_pages/insert_text_at_or_in_bookmark.html

+0

從[Help Center](http://stackoverflow.com/help /如何回答):與外部鏈接鼓勵使用資源,但請在鏈接上添加上下文,以便您的同行用戶瞭解它是什麼以及它爲什麼在那裏。如果目標網站無法訪問或永久離線,請始終引用重要鏈接中最相關的部分。 – Adam

3

我找到了一種方法使用書籤就像曼努埃爾說做到這一點:

string[] readText = File.ReadAllLines(@"p:\CARTAP1.txt"); 

    // declare objects and variables 
    object fileName = @"P:\PreciboCancelado.doc"; 
    object readOnly = false; 
    object isVisible = true; 
    object missing = System.Reflection.Missing.Value; 

    // create instance of Word 
    Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); 


    // Create instance of Word document 
    Microsoft.Office.Interop.Word.Document oWordDoc = new Document(); 


    // Open word document. 
    oWordDoc = oWordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref readOnly, 
    ref missing, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing, ref missing, ref missing, ref missing); 

    oWordDoc.Activate(); 

    // Debug to see that I can write to the document. 
    oWordApp.Selection.TypeText("This is the text that was written from the C# program! "); 
    oWordApp.Selection.TypeParagraph(); 


    // Example of writing to bookmarks each bookmark will have exists around it to avoid null. 
    if (oWordDoc.Bookmarks.Exists("Fecha")) 
     { 
      // set value for bookmarks   
      object oBookMark = "Fecha"; 
      oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = readText[2] ; 

      oBookMark = "Nombre"; 
      oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = readText[3]; 

    } 

    // Save the document. 
    oWordApp.Documents.Save(ref missing, ref missing); 


    // Close the application. 
    oWordApp.Application.Quit(ref missing, ref missing, ref missing); 
相關問題