首页 > 解决方案 > 使用 .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 来实现它吗?怎么筑巢?

谢谢!

标签: c#.netopenxml

解决方案


您需要创建一个复杂的字段。复杂字段允许您使用其他字段代码(例如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 下载中心


推荐阅读