从 ASP.NET 进行 MS Word 自动化和发布






3.50/5 (7投票s)
2007年8月13日
2分钟阅读

88468
从 ASP.NET 进行 MS Word 自动化
引言
本文档提供了从 ASP.NET 执行 MS Word 自动化的详细信息。它还包括有关在将文件发布到 Web 服务器(Windows 2000 Server / IIS 5)后使自动化功能正常工作的详细信息。
背景
许多网站提供了有关从 ASP.NET 执行自动化的详细信息。但关于使网站在发布到 Web 服务器后正常工作的信息却很少。必须分配访问权限才能从网站执行自动化。
Using the Code
以下代码片段提供了有关从 ASP.NET / C# 创建 MS Word DOC 的基本信息。我们在这里所做的是打开一个预定义的文档模板(DOT 文件),并在执行期间,将数据插入到模板中的任何所需位置,然后将 DOT 文件保存为新的 DOC 文件。示例代码显示了如何将数据/图像插入到 DOT 文件中的特定单元格中。假设模板包含我们在此期间写入数据/图像的表格。请记住添加 MS Word COM 对象库的引用(例如,MS Word 2000 的 Microsoft Word 9.0 对象库)。
// Handle parameters you don't care about in .NET
object oMissing = System.Reflection.Missing.Value;
// Predefined bookmark
object oEndOfDoc = "\\endofdoc";
// Launch MS Word
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
// Get the document template (.DOT) file
object objDocTemplate = Server.MapPath("") + "\\MyTemplate\\MyTemplate.dot";
oDoc = oWord.Documents.Add(ref objDocTemplate, ref oMissing, ref oMissing,
ref oMissing);
// Forcefully hide the table GridLines
oDoc.ActiveWindow.View.TableGridlines = false;
// Forcefully set the Zoom percentage to 100% when opening the document
oDoc.ActiveWindow.ActivePane.View.Zoom.Percentage = 100;
// Forcefully hide the Spelling Errors
oDoc.ShowSpellingErrors = false;
// Add text data to the cells in the Table (This can be static data or
// data retrieved from database)
oDoc.Tables.Item(1).Cell(1, 1).Range.Text = "My Document's Title";
oDoc.Tables.Item(1).Cell(2, 1).Range.Text = "My Document Description";
oDoc.Tables.Item(1).Cell(3, 1).Range.Text = "My Image Name";
// Add image to the cell in the Table
string MyImage = "img/MyImage.jpg";
oDoc.Tables.Item(1).Cell(4, 1).Range.InlineShapes.AddPicture(myImage,
ref linktofile as object, ref savewithfile, ref range);
// Save opened template as another .doc file
Object oSaveAsFile = Server.MapPath("") + "\\MyTemplate\\MyDocument.doc";
oDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);
// Close the document, destroy the object and Quit Word
object SaveChanges = true;
oDoc.Close(ref SaveChanges, ref oMissing, ref oMissing);
oDoc = null;
oWord.Quit(ref SaveChanges, ref oMissing, ref oMissing);
完成所需的编码后,从 DEBUG 模式(即从 .NET IDE 执行)运行 Web 应用程序时,Web 应用程序将运行,并在指定事件发生时执行自动化任务,并创建文档文件(MyDocument.doc)。
但是,如果将此代码发布并托管在 IIS 中,在尝试执行自动化时,如果没有授予权限,将显示以下错误。
为了消除这个令人烦恼的问题,请执行以下任务
- 创建一个新的 Windows 用户(例如 MSWordUser)。请注意,此用户应属于“管理员”组。
- 从“开始”菜单运行 dcomcnfg 实用程序(“开始”>“运行”> dcomcnfg)。
- 从“应用程序”选项卡中选择“Microsoft Word Document”。
- 单击“默认安全”选项卡。
- 在“默认访问权限”下单击“编辑默认”按钮。包括 MSWordUser 以具有“允许访问”权限。
- 在“默认启动权限”下单击“编辑默认”按钮。包括 MSWordUser 以具有“允许启动”权限。
现在尝试运行应用程序,如果即使执行上述任务后错误仍然存在,请在 Web.Config 文件中包含以下内容,就完成了!DOC 文件将被创建并保存,而不会出现任何问题。

要从网站(浏览器)查看创建的文档文件,只需在所有自动化代码下方,使用 Response.Redirect()
重定向到创建的 Word 文档即可。