简体   繁体   中英

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.

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.

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:

    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. Perhaps this link helps you http://gregmaxey.mvps.org/word_tip_pages/insert_text_at_or_in_bookmark.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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