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

喜欢而已 提交于 2019-12-01 09:27:15

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:

Here is the text output:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!