【Azure App Service】使用Microsoft.Office.Interop.Word来操作Word文档,部署到App Service后报错COMException

本文涉及的产品
应用实时监控服务-用户体验监控,每月100OCU免费额度
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
应用实时监控服务-应用监控,每月50GB免费额度
简介: System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).

问题描述

在.NET项目中,使用Microsoft.Office.Interop.Word组件来操作Word文档,使用了Microsoft.Office.Interop.Word.Document对象中的Open和SaveAs方法。

##打开文件

doc = app.Documents.Open(ref inputFile, ref nullobj, ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

##保存文件,关闭文件

doc.SaveAs(ref outputFile, ref nullobj, ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

doc.Close(ref nullobj, ref nullobj, ref nullobj);

但是,在部署到App Service后,遇到 “System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).“ 错误。

完整的错误信息为:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).

at Services.Api.Controllers.v1.FileoOerationController.GetFileBasedOnTemplates() in D:\FileOperationController.cs:line 328

at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)

at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)

at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)

at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()

--- End of stack trace from previous location ---

at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)

at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)

at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)

at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)

at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)

at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

报错截图:

 

问题解答

Azure App Service 不支持Microsoft.Office.Interop,该扩展需要依赖本地安装的Office, App Service为Sandbox环境,无法安装Office。

替代方案是使用 Open-XML-SDK 来操作 Word 文档。

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
OpenAndAddTextToWordDocument(args[0], args[1]);
static void OpenAndAddTextToWordDocument(string filepath, string txt)
{
    // Open a WordprocessingDocument for editing using the filepath.
    WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true);
    if (wordprocessingDocument is null)
    {
        throw new ArgumentNullException(nameof(wordprocessingDocument));
    }
    // Assign a reference to the existing document body.
    MainDocumentPart mainDocumentPart = wordprocessingDocument.MainDocumentPart ?? wordprocessingDocument.AddMainDocumentPart();
    mainDocumentPart.Document ??= new Document();
    mainDocumentPart.Document.Body ??= mainDocumentPart.Document.AppendChild(new Body());
    Body body = wordprocessingDocument.MainDocumentPart!.Document!.Body!;
    // Add new text.
    Paragraph para = body.AppendChild(new Paragraph());
    Run run = para.AppendChild(new Run());
    run.AppendChild(new Text(txt));
    // Dispose the handle explicitly.
    wordprocessingDocument.Dispose();
}

(Open and add text to a word processing document : https://learn.microsoft.com/en-us/office/open-xml/word/how-to-open-and-add-text-to-a-word-processing-document?tabs=cs-0%2Ccs-1%2Ccs-2%2Ccs-3%2Ccs

 

附录:使用Microsoft.Office.Interop操作Word的代码


Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = null;
string inputFilePath = ".\\testfile1.docx";
string outputFilePath = ".\\testfile1.docx";
object nullobj = Type.Missing;
object inputFile = inputFilePath;
object outputFile = outputFilePath;
object oStory = WdUnits.wdStory;
object oMove = WdMovementType.wdMove;
Dictionary<string, string> datas = new Dictionary<string, string>();
datas["name"] = "namexxxxxxxxx";
datas["code"] = "codexxxxxxxxxx";
app.Visible = false;
app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
doc = app.Documents.Open(ref inputFile, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
app.Selection.HomeKey(ref oStory, ref oMove);
app.Options.ReplaceSelection = true;
foreach (var item in datas)
{
    app.Selection.Find.ClearFormatting();
    app.Selection.Find.Replacement.ClearFormatting();
    string oldStr = item.Key;
    string newStr = item.Value;
    if (newStr == null)
    {
        newStr = "";
    }
    app.Selection.Find.Text = oldStr;
    app.Selection.Find.Replacement.Text = newStr;
    app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
        ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
        ref objReplace, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
}
doc.SaveAs(ref outputFile, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
if (doc != null)
{
    doc.Close(ref nullobj, ref nullobj, ref nullobj);
    doc = null;
}
if (app != null)
{
    app.Quit(ref nullobj, ref nullobj, ref nullobj);
    app = null;
}

 

 

参考资料

Can we use Microsoft.Office.Interop.excel.dll in Azure funtions? https://stackoverflow.com/questions/51552404/can-we-use-microsoft-office-interop-excel-dll-in-azure-funtions

App Service Sandbox: https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox

Open and add text to a word processing document : https://learn.microsoft.com/en-us/office/open-xml/word/how-to-open-and-add-text-to-a-word-processing-document?tabs=cs-0%2Ccs-1%2Ccs-2%2Ccs-3%2Ccs

?? 和 ??= 运算符 - Null 合并操作符: https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/null-coalescing-operator

 


当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

相关文章
|
2月前
|
JSON 小程序 JavaScript
uni-app开发微信小程序的报错[渲染层错误]排查及解决
uni-app开发微信小程序的报错[渲染层错误]排查及解决
689 7
|
4月前
|
开发框架 .NET Windows
【App Service】在App Service中配置Virtual applications and directories,访问目录中的静态文件报错404
【App Service】在App Service中配置Virtual applications and directories,访问目录中的静态文件报错404
|
4月前
|
安全 前端开发 网络安全
【Azure App Service】访问App Service应用报错 SSL: WRONG_VERSION_NUMBER
【Azure App Service】访问App Service应用报错 SSL: WRONG_VERSION_NUMBER
148 0
|
3月前
|
安全
猿大师办公助手在线编辑微软Office/金山wps网页组件COM加载项启用说明
猿大师办公助手是一款独特的在线编辑Office插件,不同于其他厂商的弹窗模式,它真正实现了网页内嵌本机Office。其COM加载项可在Office主菜单栏增加PageHi子菜单,提供文件保存、打印等功能,并能控制文档操作权限。安装后,默认自动启动COM加载项,但需注意可能被禁用或拦截,必要时需手动启用。对于WPS和微软Office,均有详细的启用步骤。
69 3
猿大师办公助手在线编辑微软Office/金山wps网页组件COM加载项启用说明
|
4月前
|
人工智能 自然语言处理 安全
微软会将ChatGPT整合纳入Office套件吗?
微软会将ChatGPT整合纳入Office套件吗?
|
7月前
|
Web App开发 JavaScript 前端开发
2024年纯前端VUE在线编辑微软Office/金山WPS的Word/Excel文档
现在,随着数字化进程渗透到到各行各业,数据安全已经成为了数字化革命中的重要组成部分,而在线Office成在OA、ERP、文档系统中得到了广泛的应用,为我国的信息化事业也做出了巨大贡献。随着操作系统、浏览器及Office软件的不断升级和更新换代,加上国家对信息化、数字化系统要求的不断提升,一些厂家的WebOffice控件产品不断被淘汰出局,而现存的几个产品也存在以下几个问题:
736 9
2024年纯前端VUE在线编辑微软Office/金山WPS的Word/Excel文档
|
7月前
微软Office 2019
微软办公软件套件Microsoft Office 2019 专业增强版2024年4月批量许可版更新推送!Office2019正式版2018年10月份推出,主要为多人跨平台办公与团队协作打造。Office2019整合对过去三年在Office365里所有功能,包括对Word、Excel、PowerPoint、Outlook、Project、Visio、Access、Publisher的更新。
166 2
|
7月前
|
Web App开发 安全 前端开发
新一代WebOffice高版本谷歌Chrome打开、编辑、保存微软Office/金山WPS解决方案大盘点
随着互联网技术的不断发展,越来越多的企业开始采用在线办公模式,微软Office Word 是最好用的文档编辑工具,然而doc、docx、xls、xlsx、ppt、pptx等格式的Office文档是无法直接在浏览器中直接打开的,如果可以实现Web在线预览编辑OffIce,肯定会还带来了更高效、便捷的办公体验,为我们的工作带来了更多可能性。
843 12
|
人工智能 自然语言处理 Oracle
WAIC 2023 | 微软Office产品团队技术负责人蔡玮鑫:Copilot中大语言模型应用实践经验
WAIC 2023 | 微软Office产品团队技术负责人蔡玮鑫:Copilot中大语言模型应用实践经验
156 0
|
Web App开发 安全 内存技术
新版谷歌Chrome取消对PPAPI插件支持后,浏览器网页打开编辑保存微软Office、金山WPS文档解决方案
最近陆续看到一些大学发布公告,谷歌Chrome取消了对PPAPI插件支持,导致某些在线Office厂家产品将无法在谷歌Chrome107及以上版本运行,被迫更换360浏览器或者使用低版本Chrome浏览器苟延残喘。
414 0
新版谷歌Chrome取消对PPAPI插件支持后,浏览器网页打开编辑保存微软Office、金山WPS文档解决方案