How to read values from a table in a word doc using C#
Asked Answered
D

1

5

I'm trying to connect to a Microsoft word document (.docx) to read values from tables located in the .docx. I'm using Open-XML SDK 2.0 to make the connection to the .docx file. So far after looking for examples and ideas, I have this,

public static string TextFromWord(string file)
{
  const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    StringBuilder textBuilder = new StringBuilder();
    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(filename,false))
      {
          //Manage namespaces to perform Xpath queries
          NameTable nt = new NameTable();
          XmlNamespaceManager nsManger = new XmlNamespaceManger(nt);
          nsManager.AddNamespace("w", wordmlNamespace);

          //Get the document part from the package.
          //Load the XML in the document part into an XmlDocument instance.
          XmlDocument xdoc = new XmlDocument(nt);
          xdoc.Load(wdDoc.MainDocumentPart.GetStream());

          XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
          foreach (XmlNode paragraphNode in paragraphNodes)
          {
            XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsmanager);
            foreach (System.Xml.XmlNode textNode in textNodes)
            {
              textBuilder.Append(textNode.InnerText);
            }
            textBuilder.Append(Environment.NewLine);
          }

         }
      return textBuilder.ToString();
}

The code works when there is just text in the .docx but fails when the text is in tables. Is there a way to fix this so it can work with tables in a .docx?

Demilune answered 2/8, 2017 at 16:31 Comment(0)
O
10

Try the following simple re-write of your method. It replaces your System.XML calls and namespace items with OpenXML elements (Document, Body, Paragraph, Table, Row, Cell, Descendants, etc) . Please install and use the OpenXML 2.5 SDK.

    public static string TextFromWord(string filename)
    {
        StringBuilder textBuilder = new StringBuilder();
        using (WordprocessingDocument wDoc = WordprocessingDocument.Open(filename, false))
        {
            var parts = wDoc.MainDocumentPart.Document.Descendants().FirstOrDefault();
            if (parts != null)
            {
                foreach (var node in parts.ChildElements)
                {
                    if(node is Paragraph)
                    {
                        ProcessParagraph((Paragraph)node, textBuilder);
                        textBuilder.AppendLine("");
                    }

                    if (node is Table)
                    {
                        ProcessTable((Table)node, textBuilder);
                    }
                }
            }
        }
        return textBuilder.ToString();
    }

    private static void ProcessTable(Table node, StringBuilder textBuilder)
    {
        foreach (var row in node.Descendants<TableRow>())
        {
            textBuilder.Append("| ");
            foreach (var cell in row.Descendants<TableCell>())
            {
                foreach (var para in cell.Descendants<Paragraph>())
                {
                    ProcessParagraph(para, textBuilder);
                }
                textBuilder.Append(" | ");
            }
            textBuilder.AppendLine("");
        }
    }

    private static void ProcessParagraph(Paragraph node, StringBuilder textBuilder)
    {
        foreach(var text in node.Descendants<Text>())
        {
            textBuilder.Append(text.InnerText);
        }
    }

Note - this code will only work on simple Word documents that consist of Paragraphs and Tables. This code has not been tested on complex word documents.

The following document was processed with the above code in a Console app:

enter image description here

Here is the text output:

enter image description here

Occult answered 8/8, 2017 at 21:4 Comment(1)
How can you read Numbers or Un-Ordered lists in MS Word where you get the list type and numbering?Cordillera

© 2022 - 2024 — McMap. All rights reserved.