提取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文件。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM