我正在尝试打开.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,这是任何解决方案,而无需启动吗?

有帮助吗?

解决方案

两种可能性:要么使用 微软的规格 为.doc格式编写自己的解析器,或将现有库用于目的(例如,从 敏捷)。除非您有几年的空闲时间来完成这项任务,否则后者显然是正确的选择。

其他提示

上次我这样做(通过C ++的COM),我回想起应用程序接口中的“可见”属性(true =可见)。

但是,在我看来,默认值是错误的,因此您必须将其设置为真实才能使单词出现。

不管用户是否可以看到单词,您仍然会在任务管理器中看到winword.exe(或今天称为今天的exe)。我认为没有启动单词(是否在幕后)的情况下通过此界面访问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();
        }
    }
}

正常工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top