简体   繁体   English

如何在确切位置将文本插入到现有Word文档C#中?

[英]How to insert text to an existing Word Document C# at an exact position?

I need your help with inserting text in a particular area in a word document. 在Word文档的特定区域插入文本时,我需要您的帮助。

I have a following code that inserts text from a .txt file to the Word document, but I need it to be placed in an exact area not just anywhere. 我有以下代码,可将文本从.txt文件插入到Word文档中,但是我需要将其放置在确切的区域中,而不是放置在任何地方。

My Code: 我的代码:

        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]);

I found a way to do it using bookmarks just as Manuel stated: 正如Manuel所说,我找到了一种使用书签的方法:

    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);

You can try it with a bookmark in Word. 您可以在Word中使用书签来尝试。 Perhaps this link helps you http://gregmaxey.mvps.org/word_tip_pages/insert_text_at_or_in_bookmark.html 也许此链接可以帮助您http://gregmaxey.mvps.org/word_tip_pages/insert_text_at_or_in_bookmark.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM