提取Word里的文本内容 C#

     using DocumentFormat.OpenXml.Packaging;  
     public
static string TextFromWord(string path) { const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; StringBuilder textBuilder = new StringBuilder(); using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(path, false)) { // Manage namespaces to perform XPath queries. NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(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); } } var result = textBuilder.ToString(); return result; }

 

异常情况:抛出异常:文件包含损坏的数据

解决办法:把doc文件转化为docx文件,可搜索在线转化网站。之后就可以使用docx文件。

posted @ 2018-03-30 11:29  向萧  阅读(1914)  评论(0编辑  收藏  举报