簡體   English   中英

使用OpenXML創建單詞添加

[英]Creating word add in with OpenXML

我是VSTO和OpenXML的新手,我想開發一些Word加載項。 此加載項應使用OpenXML,因此可以編輯打開的文檔嗎? 例如,我已經打開Word文檔,並且想在單擊按鈕時使用OpenXML替換一些文本。

所以我有這段代碼。

var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;
Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);

        //edit document using OpenXml here

Globals.ThisAddIn.Application.Documents.Open(fileFullName);

我發現這可以使用OpenXML將文本添加到Word中如何:打開並將文本添加到文字處理文檔中(Open XML SDK)

但是我不知道如何使它們一起工作。

有人可以幫我嗎,謝謝

你可以做類似的事情。

public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("Hello world!");
        docText = regexText.Replace(docText, "Hi Everyone!");

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}

請閱讀此帖子以獲取更多詳細信息。

https://msdn.microsoft.com/zh-CN/library/office/bb508261.aspx

這就是我解決的方法:

private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;

            Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);


            OpenAndAddTextToWordDocument(fileFullName, "[USER_NAME]");


            Globals.ThisAddIn.Application.Documents.Open(fileFullName);
        }

        public static void OpenAndAddTextToWordDocument(string filepath, string txt)
        {
            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);

            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            // Add new text.
            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text(txt));

            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM