在不启动MSWord的情况下读取.doc文件

我正在尝试打开.doc文件并阅读其内容。 但是,如果不启动MSWord,我无法找到任何方法。

现在我有以下代码:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); object nullObject = System.Reflection.Missing.Value; object file = @"C:\doc.doc"; Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(ref file, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject); doc.ActiveWindow.Selection.WholeStory(); doc.ActiveWindow.Selection.Copy(); IDataObject data = Clipboard.GetDataObject(); string text = data.GetData(DataFormats.Text).ToString(); doc.Close(ref nullObject, ref nullObject, ref nullObject); app.Quit(ref nullObject, ref nullObject, ref nullObject); 

但它推出了MSWord,任何解决方案都可以不启动它吗?

两种可能性:要么使用Microsoft的规范为.doc格式编写自己的解析器,要么使用现有的库(例如,来自Aspose )。 除非你有几年的时间花在这项任务上,否则后者显然是正确的选择。

上次我这样做(通过C ++中的COM),我回忆起Application界面中的’Visible’属性(true = visible)。

但是,在我看来,默认值为false,因此您必须将其设置为true才能显示Word。

无论用户是否可以看到Word,您仍然可以在任务管理器中看到winword.exe(或者今天所谓的任何内容)。 我不认为有一种方法可以通过这个界面访问Word而不启动Word(幕后或不)。

如果您根本不想启动Word,则可能需要找到另一种解决方案。

使用“添加引用” – >“浏览” – >“Code7248.word_reader.dll”添加命名空间

从给定的URL下载DLL:

sourceforge.net/p/word-reader/wiki/Home

(一个简单的.NET库,与C ++的.NET 2.0,3.0,3.5和4.0兼容。它目前只能从.doc或.docx文件中提取原始文本。)

示例代码在C#中的简单控制台中:

 using System; using System.Collections.Generic; using System.Text; //add extra namespaces using Code7248.word_reader; namespace testWordRead { class Program { private void readFileContent(string path) { TextExtractor extractor = new TextExtractor(path); string text = extractor.ExtractText(); Console.WriteLine(text); } static void Main(string[] args) { Program cs = new Program(); string path = "D:\Test\testdoc1.docx"; cs.readFileContent(path); Console.ReadLine(); } } } 

它工作正常。