首页 > 解决方案 > 使用 OpenXML 在 word 中创建动态项目的编号列表

问题描述

我有一个要求,我的 C# 代码将从数据库中生成一个项目列表,这些项目实际上是订单指令,即如何下订单。该编号列表将包含一些超链接和一些粗体的折扣代码。

我不确定如何获取该列表并将其转换为具有正确格式的单词编号列表。请提供任何帮助。列表示例如下:

  1. 导航到http://www.google.com/ordername/basket.aspx?quantity=1&productId=23334
  2. 输入更新代码:DG%$2&*JH,然后按“更新”按钮。
  3. 按照结帐流程并使用您选择的方法付款。

所有这些都是在运行时生成的,值来自 DB

我尝试使用Open XML Productivity Tool来获取代码,但是它上面的每个列表项都分为多个部分然后附加,这太复杂了。

我还需要在文档中间使用此列表 - 在此处使用 .dotx。

我尝试过的代码部分可以在没有任何超链接和粗体文本的情况下工作,如下所示:

private static void AddBulletList(List<Run> runList, MainDocumentPart mainDocumentPart)
    {
        Body body = mainDocumentPart.Document.Body;
        Paragraph parentPara = body.Descendants<Paragraph>().FirstOrDefault(k => k.InnerText.Contains("text after which I need numbered list"));
        Paragraph emptyPara = new Paragraph(new Run(new Text("")));
        parentPara.InsertAfterSelf(emptyPara);
        NumberingDefinitionsPart numberingPart = mainDocumentPart.NumberingDefinitionsPart;
        var numberId = numberingPart.Numbering.Elements<NumberingInstance>().Count() + 1;
        foreach (Run runItem in runList)
        {
            // Create items for paragraph properties
            var numberingProperties = new NumberingProperties(new NumberingLevelReference() { Val = 0 }, new NumberingId() { Val = numberId });
            var spacingBetweenLines1 = new SpacingBetweenLines() { After = "60" };  // Get rid of space between bullets
            var indentation = new Indentation() { Left = "720", Hanging = "360" };  // correct indentation 

            ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
            RunFonts runFonts1 = new RunFonts() { Ascii = "Arial", HighAnsi = "Arial", EastAsia = "Calibri", ComplexScript = "Arial" };
            FontSize fontSize1 = new FontSize() { Val = "20" };
            FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "20" };
            paragraphMarkRunProperties1.Append(runFonts1);
            paragraphMarkRunProperties1.Append(fontSize1);
            paragraphMarkRunProperties1.Append(fontSizeComplexScript1);

            // create paragraph properties
            var paragraphProperties = new ParagraphProperties(numberingProperties, spacingBetweenLines1, indentation, paragraphMarkRunProperties1);

            // Create paragraph 
            var newPara = new Paragraph(paragraphProperties);

            // Add run to the paragraph
            newPara.AppendChild(runItem);

            // Add one bullet item to the body
            //body.AppendChild(newPara);
            emptyPara.InsertAfterSelf(newPara);
        }
    }

标签: c#asp.net-mvcms-wordopenxmlopenxml-sdk

解决方案


推荐阅读