打开并修改Word文档

19

我想使用 "Microsoft.Office.Interop.Word" 打开保存在我的服务器上的 Word 文件。 这是我的代码:

    object missing = System.Reflection.Missing.Value;
    object readOnly = false;
    object isVisible = true;
    object fileName = "http://localhost:52099/modelloBusta/prova.dotx";
    Microsoft.Office.Interop.Word.ApplicationClass applicationWord = new Microsoft.Office.Interop.Word.ApplicationClass();
    Microsoft.Office.Interop.Word.Document modelloBusta = new  Microsoft.Office.Interop.Word.Document();

    try
    {

        modelloBusta = applicationWord.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref  missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible,ref missing, ref missing, ref missing, ref missing);
        modelloBusta.Activate();



    }
    catch (COMException eccezione){
        Console.Write(eccezione);
        modelloBusta.Application.Quit(ref missing, ref missing, ref missing);

    }

在Windows任务管理器中存在该进程,但“Word文档”未显示(应用程序未启动)。 问题出在哪里? 提前致谢。


1
尝试查看OpenXML SDK文档,并进行下载 - Elyor
而对于你的问题,非常好的答案是:1->在流字段中从你的远程 URL 中读取 *.dotx 文件。2->OpenXML Word Document 在此合并你的逻辑... - Elyor
尝试使用docx类型的文档,这样您就可以将它们视为xml。此外,您必须在服务器上拥有已许可和激活的Word副本才能使用这些功能。 - user220583
1
我用这个命令解决了问题:applicationWord.Visibile = true;希望能帮到别人。 - ilamaiolo
1
除非您必须指定特殊参数(例如只读),否则无需使用“ref missing”虚拟参数,只需使用applicationWord.Documents.Open(fileName);附注:较新的.NET版本使用动态参数解决了这个问题,请参见[此处](https://dev59.com/P3E85IYBdhLWcg3wnU4d#2690837)。因此,您可以简单地编写`applicationWord.Documents.Open(filePath,ReadOnly:true);`。 - Matt
3个回答

22
您需要确保在自动化 Word 的过程中,Word 应用程序窗口实际上是可见的:
var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;

7

首先,通过直接添加到资源中来添加office.interop的dll,然后添加此using指令:

using Microsoft.Office.Interop.Word;

使用以下代码

Application ap = new Application();
Document document = ap.Documents.Open(@"C:\invoice.docx");;

5

http://support.microsoft.com/kb/257757

微软目前不建议,也不支持从任何非交互式客户端应用程序或组件(包括ASP、ASP.NET、DCOM和NT服务)自动化Microsoft Office应用程序,因为在此环境下运行Office可能会表现出不稳定的行为和/或死锁。

http://freeword.codeplex.com/

Document document = new Document();
document.LoadFromFile("test.doct");

4
需要注意的是,尽管这种方法可行,但也有一定的限制:Spire.Doc免费版本只能处理100段落。在读取或写入文件时会执行此限制。如果需要解除限制,请升级到Spire.Doc商业版。 http://www.e-iceblue.com/Introduce/word-for-net-introduce.html - gap
这个能够打开并读取文件吗,还是只能进行转换? - Hugh Seagraves

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接