How do you access the numbering of an outline in a Word Document using C# and OpenXml?

Viewed 3880

I am trying to transfer an outline in Microsoft Word 2010 to a spreadsheet in Microsoft Excel 2010. I'm using DocumentFormat.OpenXml.Packing and Documentformat.OpenXml.Wordprocessing

I get the body of the document, and use it to get a list of all the paragraph objects:

var allParagraphs = new List<Paragraph>();
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(wordDocPath.Text, false);
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
allParagraphs = body.OfType<Paragraph>().ToList();

But I can't seem to find anything that stores the outline numbering that is next to the paragraph. Do I need to be grabbing other objects besides the paragraphs in the document to get the outline numbers, if there are any, for every paragraph?

The outline numbering I'm speaking of appears to the left of these headers in the screenshot below:

outline numbering of an outline

Unfortunately, the ParagraphProperties.OutlineLevel is null, even though I know it is part of an outline in the word document.

2 Answers

I found @varun-rathore 's answer to be very helpful in figuring out this issue today. However, my numbering scheme was very complex and I saw the task of calculating the string via NumberingLevelReference to be very daunting. I was able to solve this by installing the following nuget package:

https://www.nuget.org/packages/OpenXmlPowerTools

Once I had done that, I was able to get the numbering as follows:

var wordDoc = WordprocessingDocument.Open(doc.InputStream, false);

var mdp = wordDoc.MainDocumentPart;
var xDoc = mdp.GetXDocument();
var paragraphs = xDoc.Descendants(W.p);

foreach (var paragraph in paragraphs)
{
    var listItem = ListItemRetriever.RetrieveListItem(wordDoc, paragraph);
}
Related