簡體   English   中英

如何在確切位置將文本插入到現有Word文檔C#中?

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

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

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

您可以在Word中使用書簽來嘗試。 也許此鏈接可以幫助您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