使用打开XML文档生成.Net-添加具有NUMPAGES的复杂公式



我正在尝试在中生成一个word文档。Net的开放式XML。问题是页脚,添加了简单的文本。我可以添加一个公式吗?其中指令(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文档(创建一个复杂字段。我在下面的代码注释中简要描述了复杂字段的每个部分的用途:

static void Main(string[] args)
{
using(WordprocessingDocument document = WordprocessingDocument.Open(@"C:Userstestdocument.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);
}
}

如果你还没有,你可以随时下载openxmlSDK工具,它可以指导你如何构建WordprocessingML。你可以在这里找到它:微软下载中心。

最新更新