【问题标题】:Open XML doc generation with .Net - Add complex formula with NUMPAGES使用 .Net 打开 XML 文档生成 - 使用 NUMPAGES 添加复杂公式
【发布时间】:2020-10-26 12:17:16
【问题描述】:

我正在尝试使用 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 来实现吗? 如何筑巢?

谢谢!

【问题讨论】:

  • 您不能将字符串减 1 : (int.Parse(NUMPAGES) - 1).ToString()
  • NUMPAGES 不是 c# 变量,是 OPENXML,我可以检索未生成的 openxml 文档上的页数吗?
  • 您必须从 XML 中获取字符串值并在 c# 中进行减法。
  • xml 有“NUMPAGES”,因为是文字处理器引擎,它使用这个“NUMPAGES”命令计算页数。当我阅读“footer.xml”时,这是没有数字本身的 NUMPAGES... :(

标签: c# .net openxml


【解决方案1】:

您需要创建一个复杂的字段。复杂字段允许您使用其他字段代码(例如 NUMPAGES 字段代码)创建公式。复杂字段由运行级别上的多个部分组成。使用FieldCharclass (microsoft docs) 创建复杂字段。我在下面的代码 cmets 中简短地描述了复杂字段的每个部分的用途:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多