用C#读取docx文件(Use c# to read docx file)

 添加WindowsBase的引用

下面的方法相当于读取WORD文档的所有文字。

private string ReadAllTextFromDocx(string fileName)
{
    using (Package package = Package.Open(fileName))
    {
        Uri docxUri = new Uri("/word/document.xml", UriKind.Relative);
        PackagePart docxPart = package.GetPart(docxUri);
        XmlDocument docxXmlDocument = new XmlDocument();
        docxXmlDocument.Load(docxPart.GetStream());
        return docxXmlDocument.InnerText;
    }
}
————————

Add a reference to windowsbase

The following method is equivalent to reading all text in a word document.

private string ReadAllTextFromDocx(string fileName)
{
    using (Package package = Package.Open(fileName))
    {
        Uri docxUri = new Uri("/word/document.xml", UriKind.Relative);
        PackagePart docxPart = package.GetPart(docxUri);
        XmlDocument docxXmlDocument = new XmlDocument();
        docxXmlDocument.Load(docxPart.GetStream());
        return docxXmlDocument.InnerText;
    }
}