使用.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 download center