我想使用C#从MS Word(.doc,.docx),Excel和Powerpoint中提取文本(字符串)。请问在哪里可以找到一个免费且简单的.NET库来读取MS Office文档? 我尝试使用NPOI,但我没有找到如何使用NPOI的示例。
我想使用C#从MS Word(.doc,.docx),Excel和Powerpoint中提取文本(字符串)。请问在哪里可以找到一个免费且简单的.NET库来读取MS Office文档? 我尝试使用NPOI,但我没有找到如何使用NPOI的示例。
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非常有帮助,可以轻松地从不同类型的文档中提取文本,包括微软办公室文件。
您可以使用此项目,该项目由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 Interop。它免费且易于使用。以下是我从文档中提取所有单词的方法。
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();
然后你可以按照自己的意愿处理这些单词。
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();
}
}
}
ZipFile
对于一个zip文件(在这种情况下是docx文件)损坏的概念... - lxa简单!
这两个步骤可以帮助您完成:
1)使用Office Interop库将DOC转换为DOCX
2)使用DOCX2TXT从新的DOCX中提取文本
第一步的链接有非常好的解释和代码示例。
第二步的替代方案是在C#中解压缩DOCX文件并扫描所需的文件。您可以在此处了解ZIP文件的结构。
编辑:啊,是的,我忘了像Skurmedel一样指出,在您要进行转换的系统上必须安装Office。
我曾经做过一个docx文本提取器,它非常简单。基本上,docx和其他(新的)格式都是一个zip文件,里面有一堆XML文件。可以使用XmlReader和仅使用.NET类来提取文本。
我不再拥有代码了,看起来:(,但我找到了一个有类似solution的人。
如果您需要读取.doc和.xls文件,则可能对您不可行,因为它们是二进制格式,可能更难解析。
还有Microsoft发布的OpenXML SDK,虽然仍处于CTP阶段。
如果你正在寻找asp.net选项,除非你在服务器上安装了Office,否则Interop不会起作用。即使是这样,Microsoft也建议不要这样做。
我使用了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担任开发者大使。
DocumentFormat.OpenXml.Packaging
和DocumentFormat.OpenXml.Wordprocessing
。并且你需要引用WindowsBase.dll
才能让它正常工作。除此之外,这是一个不错的解决方案。 - Kristian Barrett