C# 如何替换模板 docx 文档和 Open XML SDK 2.0(8 月 9 日)中的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1361588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace content in template docx document and Open XML SDK 2.0 (Aug 09)?
提问by Matthew Sharpe
I have a "template" docx document which contains the desired layout, and wish to insert content using C#, but I cannot find a way to uniquely address specific sections of the document, such as paragraphs or tables. What is the best way to uniquely identify elements in the document? Thanks, Matt Sharpe.
我有一个“模板”docx 文档,其中包含所需的布局,并希望使用 C# 插入内容,但我找不到唯一解决文档特定部分(例如段落或表格)的方法。唯一标识文档中元素的最佳方法是什么?谢谢,马特夏普。
采纳答案by Ahmad Mageed
How is your template built? Does it use an underlying XML Schema loaded as part of the *.docx? Or are you using content controls off of the Developer ribbon, in which case each control is uniquely identified by a given tag name? Both of these approaches would make identifying certain sections of your document easier as you could control where tables or paragraphs would be.
你的模板是如何构建的?它是否使用作为 *.docx 的一部分加载的底层 XML 模式?或者您是否使用 Developer 功能区之外的内容控件,在这种情况下,每个控件都由给定的标记名称唯一标识?这两种方法都可以更轻松地识别文档的某些部分,因为您可以控制表格或段落的位置。
Also, you may want to consider using the Open XML SDK 2.0(uses .NET 3.5). It includes a handy Document Reflector tool that allows you to open up and inspect any Open XML document and shows how to generate the code for any element you click on.
此外,您可能需要考虑使用Open XML SDK 2.0(使用 .NET 3.5)。它包括一个方便的文档反射器工具,允许您打开和检查任何 Open XML 文档,并展示如何为您单击的任何元素生成代码。
Apart from that, to learn more about content controls you can check these posts:
除此之外,要了解有关内容控制的更多信息,您可以查看这些帖子:
回答by Jim W
Can you use document variables/fields? Just go to Insert->Quick Parts->Fields->Doc Variable, enter name of variable.
您可以使用文档变量/字段吗?只需转到插入-> 快速部件-> 字段-> 文档变量,输入变量名称。
example: http://www.codeproject.com/KB/office/Fill_Mergefields.aspx
示例:http: //www.codeproject.com/KB/office/Fill_Mergefields.aspx
You could also just use placeholder text values like "##insert_first_name##" and then do a search and replace for those variables.
您也可以只使用像“##insert_first_name##”这样的占位符文本值,然后搜索并替换这些变量。
示例:http: //geekswithblogs.net/DanBedassa/archive/2009/01/16/dynamically-generating-word-2007-.docx-documents-using-.net.aspx
回答by foson
回答by edi9999
There are several options to do this.
有几种选择可以做到这一点。
I have created a simple open-source library that will replace tags by values.
我创建了一个简单的开源库,它将按值替换标签。
For example Hi {name}
with data={name:"John"}
will be replaced by Hi John
.
例如Hi {name}
withdata={name:"John"}
将被替换为Hi John
。
Here it is : https://github.com/edi9999/docxtemplater
这是:https: //github.com/edi9999/docxtemplater
Demo: http://javascript-ninja.fr/docxgenjs/examples/demo.html