Microsoft Office Interop Excel ExportAsFixedFormat - 非常慢,图像未加载

时间:2017-01-09 09:56:51

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

我想将生成的.xlsx电子表格导出为PDF格式。 我有两个问题:

  • 导出文档的速度非常慢 - SaveAs()ExportAsFixedFormat()
  • ExportAsFixedFormat不导出图像。

我在IIS服务器上运行代码。

已配置的权限如下所示:https://support.comodo.com/index.php?/Knowledgebase/Article/View/1129/66/access-denied-exception-from-hresult-0x80070005-e_accessdenied

此存储库中的代码可以正常运行:https://github.com/aardvarkss/ExcelPDFExport

我也用EPPlus生成.xlsx文件。

代码:

   Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
   Microsoft.Office.Interop.Excel.Workbooks excelWorkbooks = app.Workbooks;
   Microsoft.Office.Interop.Excel.Workbook wkb = excelWorkbooks.Open(this.tempExcelFilePath);

   foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in wkb.Sheets)
   {
        sheet.SaveAs(this.tempPdfFilePath); // Saves the PDF correct AS I want But it cannot finish the task (waiting around 3 mins)
        sheet.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, this.tempPdfFilePath); // Export PDF without image (image currently cannot be displayed), Also slow
   }

   wkb.SaveAs(this.tempPdfFilePath); // Waiting too long and cannot be finished
   wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, "C:\\Users\\user222\\Desktop\\Sample.pdf"); // Waiting too long and cannot be finish the task

   // Closes the EXCEL.exe process in windows. If it not closes it cause errors. 
   wkb.Close(SaveChanges: false);
   excelWorkbooks.Close();
   app.Quit();

   System.Runtime.InteropServices.Marshal.ReleaseComObject(wkb);
   System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbooks);
   System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

任何想法为什么这么慢?以及如何解决我的问题?

今天开始缓慢装载。在此之前,它没有加载缓慢的问题。

1 个答案:

答案 0 :(得分:1)

  

我在IIS服务器上运行代码。

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

如果要构建在服务器端上下文中运行的解决方案,则应尝试使用已为安全无人值守执行的组件。或者,您应该尝试找到允许至少部分代码在客户端运行的替代方法。如果从服务器端解决方案使用Office应用程序,则应用程序将缺少许多成功运行的必要功能。此外,您将承担整体解决方案稳定性的风险。请在Considerations for server-side Automation of Office文章中详细了解相关内容。

我建议使用Open XML SDK,请参阅Welcome to the Open XML SDK 2.5 for Office。您也可以考虑使用专为服务器端执行而设计的第三方组件。