How to extract text from MS office documents in C#

2019-01-05 00:50发布

I was trying to extract a text(string) from MS Word (.doc, .docx), Excel and Powerpoint using C#. Where can i find a free and simple .Net library to read MS Office documents? I tried to use NPOI but i didn't get a sample about how to use NPOI.

9条回答
爷的心禁止访问
2楼-- · 2019-01-05 01:09

Simple!

These two steps will get you there:

1) Use the Office Interop library to convert DOC to DOCX
2) Use DOCX2TXT to extract the text from the new DOCX

The link for 1) has a very good explanation of how to do the conversion and even a code sample.

An alternative to 2) is to just unzip the DOCX file in C# and scan for the files you need. You can read about the structure of the ZIP file here.

Edit: Ah yes, I forgot to point out as Skurmedel did below that you must have Office installed on the system on which you want to do the conversion.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-05 01:12

Tika is very helpful and easy to extract text from different kind of documents, including microsoft office files.

You can use this project which is such a nice piece of art made by Kevin Miller http://kevm.github.io/tikaondotnet/

Just simply add this NuGet package https://www.nuget.org/packages/TikaOnDotNet/

and then, this one line of code will do the magic:

var text = new TikaOnDotNet.TextExtractor().Extract("fileName.docx  / pdf  / .... ").Text;
查看更多
姐就是有狂的资本
4楼-- · 2019-01-05 01:17

I did a docx text extractor once, and it was very simple. Basically docx, and the other (new) formats I presume, is a zip-file with a bunch of XML-files instead. The text can be extracted using a XmlReader and using only .NET-classes.

I don't have the code anymore, it seems :(, but I found a guy who have a similar solution.

Maybe this isn't viable for you if you need to read .doc and .xls files though, since they are binary formats and probably much harder to parse.

There is also the OpenXML SDK, still in CTP though, released by Microsoft.

查看更多
登录 后发表回答