c# - ASP.NET WebApi 无法与 Azure 中的 COM (Excel) 配合使用

标签 c# excel azure asp.net-web-api com

COM 对象存在一些问题

我有一个 Web API Controller ,可以创建和保存 Excel 文件。

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            excel.Workbooks.Add();

            Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet;

            try
            {

                workSheet.Cells[1, "A"] = "Id";
               -//- 
                int row = 2; 
                foreach (var _c in db.Clients)
                {
                    workSheet.Cells[row, "A"] = _c.ClientId;
                    -//-                     

                    row++;
                }

                        workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);

                fileName = string.Format(@"{0}/ExcelData.xlsx", System.Web.HttpContext.Current.Server.MapPath("~/Reports"));

               workSheet.SaveAs(fileName); 

创建后 Controller 返回该文件的 url。 在我的 localHost 上它运行得很好,但是在作为主机部署到 Azure 云后,我遇到了一个异常(exception):

异常消息:

"Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."
ExceptionType:
"System.Runtime.InteropServices.COMException"
Message:
"An error has occurred."
StackTrace:
"   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) 

等等

我已经尝试在 x64 和 x86 之间切换 - 但没有帮助

如果有人知道如何解决这个问题,请告诉我

最佳答案

我也遇到了和你一样的问题。我找到了微软官方的说法:

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

您将看到详细信息:http://support.microsoft.com/kb/257757

我在博客中找到了这个解决方案

https://debugmode.net/2011/08/28/creating-and-updating-excel-file-in-windows-azure-web-role-using-open-xml-sdk/

关于c# - ASP.NET WebApi 无法与 Azure 中的 COM (Excel) 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072535/

相关文章:

c# - 获取 GridViewColumn 的父级

vba - 有没有办法执行单元格中包含的 VBA 代码?

c - 如果从 EXCEL 复制数据,strtok 不起作用

vba - Excel vba 在发生错误后杀死不可见的应用程序

c# - String.StartsWith 不使用波浪号 ("~") 字符 LINQ to SQL?

c# - string1 中有多少个 string2?

c# - Azure.Search.Documents v11 中的 ContinuationToken 在哪里

azure - Terraform 如何根据条件创建代码块

python - 如何从 Azure Key Vault 中的证书获取私钥?

c# - CosmosClient : Custom json converter works out of the box with NewtonSoft, 不包含 System.Text.Json