将word doc转换为html时,Asp.net页面会挂起

时间:2014-02-01 11:23:11

标签: c# html asp.net ms-word office-interop

我有一个函数用于将单词doc保存为html文件,作为基于Web的文档查看器的一部分。它返回新创建的html文件的路径,然后显示在iframe中。我已将其内容粘贴在下面以供参考。

当我从visual studio运行Web应用程序时,这一切都运行正常,但是当它安装在IIS上时,它就会挂起。未创建html文件。

在这种情况之前,该函数只能实例化Application类;我收到的错误是:

  

“检索组件{Guid-thing}的COM类工厂因以下错误而失败...”

通过转到组件服务 - >解决了这个问题。计算机 - >我的电脑 - > DCOM配置。我转到 Microsoft Word 97 - 2003 Docment 的安全属性,并将权限本地启动本地激活授予IIS用户/网络服务。之后,我还提供了远程启动远程激活权限。

当我尝试查看文档时,我在任务管理器中看到,在进程下,网络服务已打开WINWORD.exe。所以它比以前更进一步。但现在我觉得它要么挂在 wordApp.Documents.Open doc.SaveAs 行上。我已经让它在点数上保持长达十分钟,但是没有超时,或者显示错误。

Web应用程序安装在Windows Server 2003 SP2上的IIS 6中

private string WordToHTML(string filePath)
{
    string returnPath = String.Empty;
    Microsoft.Office.Interop.Word.Document doc = null;
    object missing = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Word.Application wordApp = null;

    try
    {
        // Initialise
        string serverFolderPath = Path.GetDirectoryName(filePath);
        string fileToOpen = filePath;
        string FileToSave = Path.GetFileNameWithoutExtension(fileToOpen) + ".html";

        // Open Word
        wordApp = new Microsoft.Office.Interop.Word.Application();

        // Get Doc
        doc = wordApp.Documents.Open(fileToOpen, ref missing, true, ref missing, 
                                     ref missing, ref missing, ref missing, 
                                     ref missing, ref missing, ref missing, 
                                     ref missing, false, ref missing, ref missing, 
                                     ref missing, ref missing);

        // If html file already exists, delete it 
        returnPath = String.Format("{0}\\{1}", serverFolderPath, FileToSave);  
        if (File.Exists(returnPath))
            File.Delete(returnPath);

        // Save as HTML document
        doc.SaveAs(returnPath, 10, ref missing, ref missing, 
                   ref missing, ref missing, ref missing, ref missing, 
                   ref missing, ref missing, ref missing, ref missing, 
                   ref missing, ref missing, ref missing, ref missing);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        doc.Close(ref missing, ref missing, ref missing);
        wordApp.Quit(ref missing, ref missing, ref missing);
    }
    return returnPath;
}

1 个答案:

答案 0 :(得分:1)

在代码中使用任何MS Office产品极易出现这类问题,并且(建议可能很难)你真的应该不惜一切代价避免在这里做你正在做的事情。

你最有可能遭受“无声的提示”。屏幕上应该有一个UI提示来响应,但是由于执行上下文/以及您没有登录到相关机器的事实,它永远不会出现。

使用此表单中的MS Office工作时,其他方面的问题包括处理对象时。如果你没有100%完美,那么你的应用程序中会出现大量的内存泄漏,并会随着时间的推移不断降低内存。我发现如果你编写你的代码永远不会将调用链接在一起,并且在使用它之前总是将每个对象分配给一个变量,这可以稍微容易实现(因为你可以专门处理每个对象

您还应该考虑将文档格式从97/2003升级到Office 2007以后的xml格式。文件大小明显更好,并且与最近可能为您查看网站的产品更加兼容。

您应该问,做这项工作(正确和可靠)的成本是否比仅使用Microsoft自己的“Office Web Apps”便宜,您可以通过企业内部的SharePoint或Office 365进行访问。具有竞争力的成本,让你在“完美的网络观看”中获得更多的地狱。