C# 打开和修改 Word 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16253215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open and modify Word Document
提问by ilamaiolo
I want to open a word file saved in my server using "Microsoft.Office.Interop.Word". This is my code:
我想使用“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);
}
In the windows task manager the process is present, but the "word document" doesn't appear (the application does not start). What is the problem? Thanks in advance.
在 Windows 任务管理器中,进程存在,但“word 文档”没有出现(应用程序没有启动)。问题是什么?提前致谢。
采纳答案by Dirk Vollmar
You need to make sure that the Word application window actually is made visible when automating Word like that:
您需要确保在像这样自动化 Word 时,Word 应用程序窗口实际上是可见的:
var applicationWord = new Microsoft.Office.Interop.Word.Application();
applicationWord.Visible = true;
回答by sulman
first add the dll of office.interop by adding directly to the resources then add this using directive:
首先通过直接添加到资源中来添加 office.interop 的 dll,然后添加以下 using 指令:
using Microsoft.Office.Interop.Word;
and use the following code
并使用以下代码
Application ap = new Application();
Document document = ap.Documents.Open(@"C:\invoice.docx");;
回答by PeterHapen
http://support.microsoft.com/kb/257757
http://support.microsoft.com/kb/257757
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
Microsoft 当前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)自动化 Microsoft Office 应用程序,因为 Office 可能表现出不稳定的行为和/或在此环境中运行 Office 时出现死锁。
Document document = new Document();
document.LoadFromFile("test.doct");

