简体   繁体   English

如何使用openxml sdk和c#在word文档中添加多级列表?

[英]How to add multilevel list in word document using openxml sdk and c#?

I am trying to implement multilevel list in word document programmatically using openxml sdk v2.5 and C#.我正在尝试使用 openxml sdk v2.5 和 C# 以编程方式在 word 文档中实现多级列表。 I have used the following code in order to display headings in multilevel list.我使用以下代码来在多级列表中显示标题。 I am calling the AddHeading method and passing the respective parameters as shown below.我正在调用 AddHeading 方法并传递相应的参数,如下所示。 My expected result is to be as below.我的预期结果如下。

1.  Parent
    1.1. childItem
      1.1.1. subchildItem
    1.2. childItem
2.  Parent
    2.1. childItem
3.  Parent

But the output i am getting is但我得到的输出是

1. Parent
    1. childItem
      1. subchildItem
    2. childItem
2.  Parent
    1. childItem
3.  Parent
public static void AddHeading(WordprocessingDocument document, string colorVal, int fontSizeVal, string styleId, string styleName, string headingText, int numLvlRef, int numIdVal)
        {
            StyleRunProperties styleRunProperties = new StyleRunProperties();
            Color color = new Color() { Val = colorVal };
            DocumentFormat.OpenXml.Wordprocessing.FontSize fontSize1 = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            fontSize1.Val = new StringValue(fontSizeVal.ToString());

            styleRunProperties.Append(color);
            styleRunProperties.Append(fontSize1);
            AddStyleToDoc(document.MainDocumentPart.Document.MainDocumentPart, styleId, styleName, styleRunProperties, document);

            Paragraph p = new Paragraph();
            ParagraphProperties pp = new ParagraphProperties();
            pp.ParagraphStyleId = new ParagraphStyleId() { Val = styleId };
            pp.SpacingBetweenLines = new SpacingBetweenLines() { After = "0" };

            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
            NumberingProperties numberingProperties1 = new NumberingProperties();
            NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference() { Val = numLvlRef };

            NumberingId numberingId1 = new NumberingId() { Val = numIdVal }; //Val is 1, 2, 3 etc based on your numberingid in your numbering element

            numberingProperties1.Append(numberingLevelReference1); Indentation indentation1 = new Indentation() { FirstLineChars = 0 };
            numberingProperties1.Append(numberingId1);
            pp.Append(paragraphStyleId1);
            pp.Append(numberingProperties1);
            pp.Append(indentation1);
            p.Append(pp);
            Run r = new Run();
            Text t = new Text(headingText) { Space = SpaceProcessingModeValues.Preserve };
            r.Append(t);
            p.Append(r);

            document.MainDocumentPart.Document.Body.Append(p);
        }


      public static void AddStyleToDoc(MainDocumentPart mainPart, string styleid, string stylename, StyleRunProperties styleRunProperties, WordprocessingDocument document)
        {
            StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;
            if (part == null)
            {
                part = AddStylesPartToPackage(mainPart);
                AddNewStyle(part, styleid, stylename, styleRunProperties);
            }
            else
            {
                if (IsStyleIdInDocument(mainPart, styleid) != true)
                {
                    string styleidFromName = GetStyleIdFromStyleName(document, stylename);
                    if (styleidFromName == null)
                    {
                        AddNewStyle(part, styleid, stylename, styleRunProperties);
                    }
                    else
                        styleid = styleidFromName;
                }
            }
        }

        public static string GetStyleIdFromStyleName(WordprocessingDocument doc, string styleName)
        {
            StyleDefinitionsPart stylePart = doc.MainDocumentPart.StyleDefinitionsPart;
            string styleId = stylePart.Styles.Descendants<StyleName>()
                .Where(s => s.Val.Value.Equals(styleName) &&
                    (((Style)s.Parent).Type == StyleValues.Paragraph))
                .Select(n => ((Style)n.Parent).StyleId).FirstOrDefault();

            return styleId;
        }

        public static StyleDefinitionsPart AddStylesPartToPackage(MainDocumentPart mainPart)
        {
            StyleDefinitionsPart part;
            part = mainPart.AddNewPart<StyleDefinitionsPart>();
            DocumentFormat.OpenXml.Wordprocessing.Styles root = new DocumentFormat.OpenXml.Wordprocessing.Styles();
            root.Save(part);
            return part;
        }

        public static bool IsStyleIdInDocument(MainDocumentPart mainPart, string styleid)
        {
            DocumentFormat.OpenXml.Wordprocessing.Styles s = mainPart.StyleDefinitionsPart.Styles;

            int n = s.Elements<DocumentFormat.OpenXml.Wordprocessing.Style>().Count();
            if (n == 0)
                return false;

            DocumentFormat.OpenXml.Wordprocessing.Style style = s.Elements<DocumentFormat.OpenXml.Wordprocessing.Style>()
                .Where(st => (st.StyleId == styleid) && (st.Type == StyleValues.Paragraph))
                .FirstOrDefault();
            if (style == null)
                return false;

            return true;
        }

        private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename, StyleRunProperties styleRunProperties)
        {
            DocumentFormat.OpenXml.Wordprocessing.Styles styles = styleDefinitionsPart.Styles;

            DocumentFormat.OpenXml.Wordprocessing.Style style = new DocumentFormat.OpenXml.Wordprocessing.Style()
            {
                Type = StyleValues.Paragraph,
                StyleId = styleid,
                CustomStyle = false
            };
            style.Append(new StyleName() { Val = stylename });
            style.Append(new BasedOn() { Val = "Normal" });
            style.Append(new NextParagraphStyle() { Val = "Normal" });
            style.Append(new UIPriority() { Val = 900 });

            styles.Append(style);
        }

To use multi-level lists in Microsoft Word, you need to ensure that:要在 Microsoft Word 中使用多级列表,您需要确保:

  1. you have the desired multi-level list set up correctly in your numbering definitions part (meaning your w:numbering element contains a w:num and corresponding w:abstractNum that specifies the different list levels);您在编号定义部分正确设置了所需的多级列表(意味着您的w:numbering元素包含一个w:num和相应的w:abstractNum ,用于指定不同的列表级别);
  2. you have one style for each list level that references both the numbering ID specified by the w:num element and the desired list level;每个列表级别都有一种样式,它同时引用w:num元素指定的编号 ID 和所需的列表级别; and
  3. your paragraphs reference the correct style for the list level.您的段落引用了列表级别的正确样式。

Please have a look at my answers on how to create multi-level ordered lists with Open XML and display multi-level lists in Word documents using C# and the Open XML SDK for further details and explanations.请查看我关于如何使用 Open XML 创建多级有序列表使用 C# 和 Open XML SDK 在 Word 文档中显示多级列表的答案,以获取更多详细信息和说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM