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

时间:2016-07-07 18:17:06

标签: c#

我需要你的帮助,在word文档的特定区域插入文本。

我有一个以下代码,可以将.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]);

2 个答案:

答案 0 :(得分:3)

我发现了一种使用书签的方法,正如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);

答案 1 :(得分:0)

您可以使用Word中的书签进行尝试。也许此链接可以帮助您http://gregmaxey.mvps.org/word_tip_pages/insert_text_at_or_in_bookmark.html