Replace Placeholders in word document with c#

岁酱吖の 提交于 2019-12-04 06:51:47

The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files. With that in mind you have a couple of approaches.

  1. You can use the Open XML SDK located at http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en

  2. You can unzip the docx file, do a search and replace for your tokens, and zip it back up.

There is a website at openxmldeveloper.org that is just for this kind of thing. Also, bear in mind that they are already shipping a beta version 2 of the SDK.

Eric White has touched on exactly this subject in a blog article detailing a program meant to validate source snippets embedded in DocX files. Beyond just that article I highly recommend reading his series on Office Open XML and C#.

I used this one:

IEnumerable test2 = from element in body.Elements() where element.InnerText.Contains("sdt") select element;

Sebastian Müller

By the way using xml I found this solution that finds ALL sdt-nodes

 NameTable nt = new NameTable();
        XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
        nsManager.AddNamespace("w", wordmlNamespace);

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(doc.MainDocumentPart.GetStream());

        XmlNodeList nodeList = xDoc.SelectNodes(@"./w:document/w:body//w:sdt", nsManager);

It works but doesn't the Open XML Format SDK 2.0 give me any chance for this?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!