首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用OpenXML创建word添加

使用OpenXML创建word添加
EN

Stack Overflow用户
提问于 2017-11-26 10:17:20
回答 2查看 832关注 0票数 1

我是VSTO和OpenXML的新手,我想开发一些单词插件。这个外接程序应该使用OpenXML,所以可以编辑打开的文档吗?例如,我打开了Word文档,我想使用OpenXML按钮点击替换一些文本。

所以我有这个密码。

代码语言:javascript
复制
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 如何:打开文本并将文本添加到文字处理文档(Open )将文本添加到单词

但我想不出怎么让他们一起工作。

有人能帮我吗,谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-26 11:35:08

我就是这样解决的:

代码语言:javascript
复制
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();
        }

    }
票数 1
EN

Stack Overflow用户

发布于 2017-11-26 10:22:19

你可以这样做;

代码语言:javascript
复制
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/en-us/library/office/bb508261.aspx

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47495039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档