首页 > 解决方案 > Microsoft.Office.Interop.Word - Word 在尝试打开文件时遇到错误

问题描述

我们有一个 ASP.Net Web 应用程序 (C#),它通过 Microsoft.Office.Interop.Word 打开一个 Word 文件。

首先,我意识到这不是推荐的方法,应该考虑使用 TextControl 或 Asppose 等库,我们将考虑用这样的库替换 Microsoft.Office.Interop.Word 的使用。

但是,在短期内,我想让它工作并且我们拥有的代码在我的开发机器上工作,客户端的测试服务器而不是他们的 UAT 服务器。

客户端的测试服务器和 UAT 服务器看似相同,我尝试查看各种 DCOM 配置设置,但并不高兴。

我查看了有关 Microsoft.Office.Interop.Word 的其他 Stack Overflow 问题,但没有任何建议有帮助。

为了帮助测试问题,我整理了一个简单的测试应用程序,它尝试使用以下代码打开 Word 文档

var wordApplication = new Application();            
var wordDocument = wordApplication.Documents.Open(txtPath.Text);
wordApplication.Visible = true;

运行 Word 进程时会出现在任务管理器中,但会出现以下错误。我显然已经检查了文件权限等。欢迎提出任何建议。

在此处输入图像描述

标签: c#asp.net

解决方案


以下演示项目展示了如何将 Word 文档文件上传到 Web 服务器,然后用于Microsoft.Office.Interop.Word读取文件。

先决条件

  • 安装在 Web 服务器计算机上的 MS Word。(打开 Word 以确保没有 MessageBox 出现——例如“Microsoft Word 不是您查看和编辑文档的默认程序...”)
  • 网站包含一个名为:Uploads 的文件夹

创建 ASP .NET Web 应用程序

与 2017 年相比

  • 打开 Visual Studio
  • 展开安装
  • 展开Visual C#
  • 点击网页
  • 选择ASP.NET Web 应用程序 (.NET Framework)
  • 点击确定
  • 选择
  • 点击确定

与 2019 年相比

  • 打开 Visual Studio
  • 单击无代码继续
  • 单击文件
  • 选择新建
  • 选择项目
  • C# Windows 网页
  • 单击ASP .NET Web 应用程序 (.NET Framework)
  • 单击下一步
  • 指定项目名称(名称:AspNetWebApp2)
  • 单击创建
  • 单击清空
  • 取消选中为 HTTPS 配置
  • 单击创建

注意:从现在开始,VS 2017 和 VS 2019 的过程相同。

添加网络表单:

  • 在 VS 菜单中,单击项目
  • 选择添加新项目
  • 选择Web 表单(名称:default.aspx)
  • 点击添加

打开解决方案资源管理器

  • 在 VS 菜单中,单击查看
  • 选择解决方案资源管理器

在解决方案资源管理器中,双击“default3.aspx”。将代码替换为以下内容:

默认3.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default3.aspx.cs" Inherits="AspNetWebApp2.Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
         <h3> File Upload:</h3>
         <br />
         <asp:FileUpload ID="FileUpload1" runat="server" />
         <br /><br />
         <asp:Button ID="btnsave" runat="server" onclick="btnsave_Click"  Text="Save" style="width:85px" />
         <br /><br />
         <asp:Label ID="lblmessage" runat="server" />
      </div>

        <div>
            <h2>Data:</h2>
            <div>
                <asp:TextBox ID="textBoxData" runat="server" Height="336px" TextMode="MultiLine" Width="603px"></asp:TextBox>
            </div>
        </div>
    </form>
</body>
</html>

添加引用(Microsoft Word xx.0 对象库)

  • 在 VS 菜单中,单击项目
  • 选择添加参考
  • 展开COM
  • 检查Microsoft Word xx.0 对象库(例如:Microsoft Word 16.0 对象库)

在解决方案资源管理器中,双击“default3.aspx.cs”并将代码替换为以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;

namespace AspNetWebApp2
{
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            bool isVisible = true;
            StringBuilder sb = new StringBuilder();
            Word.Application wordApp = null;
            Word.Document doc = null;
            Word.Documents documents = null;

            if (FileUpload1.HasFile)
            {
                try
                {
                    sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);

                    //saving the file

                    string localDir = System.IO.Path.Combine(Server.MapPath("."), "Uploads");

                    if (!System.IO.Directory.Exists(localDir))
                    {
                        string errMsg = String.Format("<script>alert('Error - Folder does not exist ({0})');</script>", localDir.Replace(@"\",@"\\"));
                        Response.Write(errMsg);
                    }

                    string localFn = System.IO.Path.Combine(Server.MapPath("."), "Uploads", FileUpload1.FileName);
                    FileUpload1.SaveAs(localFn);

                    //Showing the file information
                    sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName);
                    sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType);
                    sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength);
                    sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName);

                    wordApp = new Word.Application();

                    //suppress displaying alerts (such as prompting to overwrite existing file)
                    wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

                    //set Word visibility
                    //wordApp.Visible = false;
                    wordApp.Visible = isVisible;

                    if (wordApp != null)
                    {
                        if (File.Exists(localFn))
                        {
                            StringBuilder sbData = new StringBuilder();

                            doc = wordApp.Documents.Open(localFn, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                            //doc = documents.Open(localFn);

                            doc.Activate();

                            foreach (Word.Paragraph p in doc.Content.Paragraphs)
                            {
                                Debug.WriteLine(p.Range.Text);
                                //Response.Write(p.Range.Text);
                                sbData.AppendLine(p.Range.Text);
                            }

                            textBoxData.Text = sbData.ToString();
                        }
                        else
                        {
                            Debug.WriteLine("Error: Filename '" + localFn + "' doesn't exist.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    sb.Append("<br/> Error <br/>");
                    sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
                }
                finally
                {
                    if (doc != null)
                    {
                        doc.Close();
                    }

                    if (documents != null)
                    {
                        documents.Close();
                    }

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        wordApp = null;
                    }
                }
            }
            else
            {
                lblmessage.Text = sb.ToString();
            }

            Debug.WriteLine(sb.ToString());
        }
    }
}

资源:


推荐阅读