我试图使用 C# 从 MS Word(.doc、.docx)、Excel 和 Powerpoint 中提取文本(字符串)。我在哪里可以找到一个免费且简单的 .Net 库来阅读 MS Office 文档?我尝试使用 NPOI,但没有获得有关如何使用 NPOI 的示例。
10 回答
对于 Microsoft Word 2007 和 Microsoft Word 2010 (.docx) 文件,您可以使用 Open XML SDK。这段代码将打开一个文档并将其内容作为文本返回。对于任何试图使用正则表达式来解析 Word 文档内容的人来说,它尤其有用。要使用此解决方案,您需要参考 DocumentFormat.OpenXml.dll,它是 OpenXML SDK 的一部分。
请参阅:http: //msdn.microsoft.com/en-us/library/bb448854.aspx
public static string TextFromWord(SPFile file)
{
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
StringBuilder textBuilder = new StringBuilder();
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file.OpenBinaryStream(), 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);
}
}
return textBuilder.ToString();
}
Tika 非常有用且易于从不同类型的文档中提取文本,包括 Microsoft Office 文件。
您可以使用这个项目,这是 Kevin Miller 制作的精美艺术品 http://kevm.github.io/tikaondotnet/
只需简单地添加这个 NuGet 包 https://www.nuget.org/packages/TikaOnDotNet/
然后,这一行代码将发挥作用:
var text = new TikaOnDotNet.TextExtractor().Extract("fileName.docx / pdf / .... ").Text;
让我稍微纠正一下 KyleM 给出的答案。我刚刚添加了两个额外节点的处理,这会影响结果:一个负责“\t”的水平制表,另一个负责“\v”的垂直制表。这是代码:
public static string ReadAllTextFromDocx(FileInfo fileInfo)
{
StringBuilder stringBuilder;
using(WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(dataSourceFileInfo.FullName, false))
{
NameTable nameTable = new NameTable();
XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(nameTable);
xmlNamespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
string wordprocessingDocumentText;
using(StreamReader streamReader = new StreamReader(wordprocessingDocument.MainDocumentPart.GetStream()))
{
wordprocessingDocumentText = streamReader.ReadToEnd();
}
stringBuilder = new StringBuilder(wordprocessingDocumentText.Length);
XmlDocument xmlDocument = new XmlDocument(nameTable);
xmlDocument.LoadXml(wordprocessingDocumentText);
XmlNodeList paragraphNodes = xmlDocument.SelectNodes("//w:p", xmlNamespaceManager);
foreach(XmlNode paragraphNode in paragraphNodes)
{
XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t | .//w:tab | .//w:br", xmlNamespaceManager);
foreach(XmlNode textNode in textNodes)
{
switch(textNode.Name)
{
case "w:t":
stringBuilder.Append(textNode.InnerText);
break;
case "w:tab":
stringBuilder.Append("\t");
break;
case "w:br":
stringBuilder.Append("\v");
break;
}
}
stringBuilder.Append(Environment.NewLine);
}
}
return stringBuilder.ToString();
}
使用 Microsoft Office 互操作。它免费且流畅。这是我如何从文档中提取所有单词的方法。
using Microsoft.Office.Interop.Word;
//Create Doc
string docPath = @"C:\docLocation.doc";
Application app = new Application();
Document doc = app.Documents.Open(docPath);
//Get all words
string allWords = doc.Content.Text;
doc.Close();
app.Quit();
然后用文字做任何你想做的事。
派对有点晚了,但是 - 现在你不需要下载任何东西 - 所有东西都已经安装了 .NET :(只需确保添加对 System.IO.Compression 和 System.IO.Compression.FileSystem 的引用)
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;
using System.Text;
using System.IO.Compression;
public static class DocxTextExtractor
{
public static string Extract(string filename)
{
XmlNamespaceManager NsMgr = new XmlNamespaceManager(new NameTable());
NsMgr.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
using (var archive = ZipFile.OpenRead(filename))
{
return XDocument
.Load(archive.GetEntry(@"word/document.xml").Open())
.XPathSelectElements("//w:p", NsMgr)
.Aggregate(new StringBuilder(), (sb, p) => p
.XPathSelectElements(".//w:t|.//w:tab|.//w:br", NsMgr)
.Select(e => { switch (e.Name.LocalName) { case "br": return "\v"; case "tab": return "\t"; } return e.Value; })
.Aggregate(sb, (sb1, v) => sb1.Append(v)))
.ToString();
}
}
}
简单的!
这两个步骤将使您到达那里:
1) 使用Office Interop 库将 DOC 转换为 DOCX
2) 使用DOCX2TXT从新的 DOCX 中提取文本
1) 的链接很好地解释了如何进行转换,甚至还有代码示例。
2) 的替代方法是在 C# 中解压缩 DOCX 文件并扫描您需要的文件。您可以在此处阅读有关 ZIP 文件结构的信息。
编辑:啊,是的,我忘了指出,正如 Skurmedel 在下面所做的那样,您必须在要进行转换的系统上安装 Office。
我曾经做过一个 docx 文本提取器,非常简单。基本上 docx 和我认为的其他(新)格式是一个带有一堆 XML 文件的 zip 文件。可以使用 XmlReader 并仅使用 .NET 类来提取文本。
我没有代码了,似乎:(,但我找到了一个有类似解决方案的人。
但是,如果您需要阅读 .doc 和 .xls 文件,这可能对您不可行,因为它们是二进制格式并且可能更难解析。
微软还发布了OpenXML SDK,尽管它仍然在 CTP 中。
如果您正在寻找 asp.net 选项,除非您在服务器上安装 office,否则互操作将无法工作。即使那样,微软也表示不要这样做。
我使用了 Spire.Doc,效果很好。 Spire.Doc 下载 它甚至可以读取实际上是 .txt 但保存为 .doc 的文档。他们有免费和付费版本。您还可以获得一个试用许可证,该许可证会从您创建的文档中删除一些警告,但我没有创建任何警告,只是搜索了它们,因此免费版本就像一个魅力。
在 C# 中从 Office 文档中提取文本的合适选项之一是GroupDocs.Parser for .NET API。以下是用于提取简单文本和格式化文本的代码示例。
提取文本
// Create an instance of Parser class
using(Parser parser = new Parser("sample.docx"))
{
// Extract a text into the reader
using(TextReader reader = parser.GetText())
{
// Print a text from the document
// If text extraction isn't supported, a reader is null
Console.WriteLine(reader == null ? "Text extraction isn't supported" : reader.ReadToEnd());
}
}
提取格式化文本
// Create an instance of Parser class
using (Parser parser = new Parser("sample.docx"))
{
// Extract a formatted text into the reader
using (TextReader reader = parser.GetFormattedText(new FormattedTextOptions(FormattedTextMode.Html)))
{
// Print a formatted text from the document
// If formatted text extraction isn't supported, a reader is null
Console.WriteLine(reader == null ? "Formatted text extraction isn't suppported" : reader.ReadToEnd());
}
}
披露:我在 GroupDocs 担任开发人员布道师。