ms-wordopenxmldocxbulletedlist

OpenXML 2 SDK - Word document - Create bulleted list programmatically


Using the OpenXML SDK, 2.0 CTP, I am trying to programmatically create a Word document. In my document I have to insert a bulleted list, an some of the elements of the list must be underlined. How can I do this?


Solution

  • Lists in OpenXML are a little confusing.

    There is a NumberingDefinitionsPart that describes all of the lists in the document. It contains information on how the lists should appear (bulleted, numbered, etc.) and also assigns and ID to each one.

    Then in the MainDocumentPart, for every item in the list you want to create, you add a new paragraph and assign the ID of the list you want to that paragraph.

    So to create a bullet list such as:

    You would first have to create a NumberingDefinitionsPart:

        NumberingDefinitionsPart numberingPart =
          mainDocumentPart.AddNewPart<NumberingDefinitionsPart>("someUniqueIdHere");
    
        Numbering element = 
          new Numbering(
            new AbstractNum(
              new Level(
                new NumberingFormat() { Val = NumberFormatValues.Bullet },
                new LevelText() { Val = "·" }
              ) { LevelIndex = 0 }
            ) { AbstractNumberId = 1 },
            new NumberingInstance(
              new AbstractNumId() { Val = 1 }
            ) { NumberID = 1 });
    
        element.Save(numberingPart);
    

    Then you create the MainDocumentPart as you normally would, except in the paragraph properties, assign the numbering ID:

        MainDocumentPart mainDocumentPart =
          package.AddMainDocumentPart();
    
        Document element = 
          new Document(
            new Body(
              new Paragraph(
                new ParagraphProperties(
                  new NumberingProperties(
                    new NumberingLevelReference() { Val = 0 },
                    new NumberingId() { Val = 1 })),
                new Run(
                  new RunProperties(),
                  new Text("Hello, ") { Space = "preserve" })),
              new Paragraph(
                new ParagraphProperties(
                  new NumberingProperties(
                    new NumberingLevelReference() { Val = 0 },
                    new NumberingId() { Val = 1 })),
                new Run(
                  new RunProperties(),
                  new Text("world!") { Space = "preserve" }))));
    
        element.Save(mainDocumentPart);
    

    There is a better explanation of the options available in the OpenXML reference guide in Section 2.9.