c# - 使用 .Net 打开 XML 文档生成 - 使用 NUMPAGES 添加复杂公式
问题描述
我正在尝试使用 Open XML 在 .Net 中生成一个 word 文档。问题在于页脚,添加了简单的文本。我可以添加一个公式,其中指令(NUMPAGES)将减少 1?
例子
run_page = new Run(new Text("Página ") { Space = SpaceProcessingModeValues.Preserve },
new SimpleField() { Instruction = "PAGE"},
new Text(" de ") { Space = SpaceProcessingModeValues.Preserve },
new SimpleField() { Instruction = "NUMPAGES - 1"});
我需要嵌套 SimpleFields 来实现它吗?怎么筑巢?
谢谢!
解决方案
您需要创建一个复杂的字段。复杂字段允许您使用其他字段代码(例如NUMPAGES
字段代码)创建公式。复杂字段由运行级别上的多个部分组成。使用FieldChar
类 ( microsoft docs ) 创建一个复杂的字段。我在下面的代码注释中简短地描述了复杂字段的每个部分的用途:
static void Main(string[] args)
{
using(WordprocessingDocument document = WordprocessingDocument.Open(@"C:\Users\test\document.docx", true))
{
// get the first paragrahp of document
Paragraph paragraph = document.MainDocumentPart.Document.Descendants<Paragraph>().First();
// clean the paragraph
paragraph.Descendants<Run>().ToList().ForEach(r => r.Remove());
// construct a complex field
// the start field char signals the start of a complex field
Run fieldStartRun = new Run(new FieldChar() { FieldCharType = FieldCharValues.Begin });
// the field code singals the field consists of a formula -> =
Run fieldFormulaCode = new Run(new FieldCode() { Space = SpaceProcessingModeValues.Preserve, Text = " = " });
// the simple field singals we want to work with the NUMPAGES field code
SimpleField pageNumberField = new SimpleField() { Instruction = "NUMPAGES" };
// The addition field code signals we want to add 2 to the NUMPAGES field
Run fieldFormulaAdditionCode = new Run(new FieldCode() { Space = SpaceProcessingModeValues.Preserve, Text = " + 2 " });
// Then end fieldchar signals the end of the complex field
Run fieldEndRun = new Run(new FieldChar() { FieldCharType = FieldCharValues.End });
// append to the paragraph
paragraph.Append(fieldStartRun, fieldFormulaCode, pageNumberField, fieldFormulaAdditionCode, fieldEndRun);
}
}
如果您还没有它,您可以随时下载 openxml SDK 工具,它可以指导您如何构建您的 WordprocessingML。您可以在此处找到它:Microsoft 下载中心。
推荐阅读
- firebase - 如何验证 Firebase 函数?
- javascript - 将参数传递给Angular中的参考模型?
- javascript - 获取“安全通道支持中发生错误”
- python - 在 soup.find_all() 中的每个文本后添加一个逗号
- reactjs - 如何确定一段代码在 ReduxJS 中应该放在哪里?
- google-ads-api - 跟踪销售回 google adwords 活动
- three.js - Gear VR 上的 Aframe 双重视觉与立体
- r - 将 2 个数据框组合在一起,将一个社交网络创建为 R 中的 1 个更大的数据框
- javascript - 如何在 React js 中加载图像?
- javascript - 从laravel控制器返回json时尝试获取非对象的属性“id”