2016-07-07 46 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); 
相关问题