首页 > 其他分享 >【Azure App Service】使用Microsoft.Office.Interop.Word来操作Word文档,部署到App Service后报错COMException

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

时间:2024-11-05 20:08:28浏览次数:1  
标签:Word Service App nullobj AspNetCore app ref Microsoft

问题描述

在.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

 

标签:Word,Service,App,nullobj,AspNetCore,app,ref,Microsoft
From: https://www.cnblogs.com/lulight/p/18528721

相关文章

  • 批量删除word文件指定页
     环境准备:系统    Windows语言Python3.8开发工具Pycharmimportosimportcomtypes.clientdefdelete_first_page(doc_path):#获取Word应用程序对象word=comtypes.client.CreateObject('Word.Application')word.Visible=0#不可见doc=w......
  • 陪玩系统源码APP中的语音聊天直播房间有哪些功能?
    陪玩系统源码APP通常采用Springboot、MybatisPlus和MySQL等后端技术栈来构建后端服务。这些技术提供了强大的数据处理能力和灵活的扩展性,能够满足高并发、低延迟的业务需求。 陪玩系统源码线上线下家政游戏陪玩前端开发框架如uniapp(针对Web和小程序)等被广泛应用于陪玩系统源......
  • 基于SSM+uniapp的营养食谱系统+LW参考示例
    1.项目介绍功能模块:用户管理、年龄类型管理、阶段食谱管理、体质类型管理、季节食谱管理、职业食谱管理等系统角色:管理员、普通用户技术栈:SSM,uniapp,Vue等测试环境:idea2024,HbuilderX,微信开发工具,MySQL5.7,Maven3,Navicat2.项目部署2.1后端部署创建数据库,导入sql通过idea......
  • 0基础读顶会论文—Kappa:一种用于无服务器计算的编程框架
    原文链接代码:快速使用kappa首先的首先,可以先去了解一下lambda架构Abstract在本文中提出了Kappa,一个简化无服务器开发的框架。它使用检查点来处理lambda函数超时,并提供并发机制,实现并行计算和协调1Introduction无服务器计算是一种新的云范例,在这种范例中,租户不是配置虚拟机(V......
  • uniapp微信小程序-分包(一看就懂)
    一、为什么要分包微信小程序每个分包的大小是2M,总体积一共不能超过20M,当然你也可以提升启动速度,降低首次加载时间,模块化开发,按需加载,提高性能。二、分包步骤 1.首先在 mainfest.jsonmp-weixin添加以下代码(启动分包)"optimization":{"subPackages":true}2.项......
  • Java SPI(Service Provider Interface)
    JavaSPI(ServiceProviderInterface)机制笔记Java的SPI(ServiceProviderInterface)机制是一种服务发现和动态加载机制,主要用于在运行时加载接口的具体实现,从而让系统能够根据需求灵活地加载不同的实现类。SPI在日志框架、数据库驱动加载、插件系统等场景中被广泛应用,极......
  • C# 删除Word文档中的段落
    在编辑Word文档时,我们有时需要调整段落的布局、删除不必要的段落以优化文档的结构和阅读体验。本文将通过以下3个简单示例演示如何使用免费.NET库删除Word文档中的段落。C#删除Word中的指定段落C#删除Word中的所有段落C#删除Word中的空白段落免费.NETWord库-FreeSp......
  • 如何用猿大师办公助手实现多人同时在线编辑Office Word文档?
    猿大师办公助手作为一个专业的网页在线编辑Office插件,集成到Web项目上非常简单,前端代码只需要简单JS调用接口就可以实现在线编辑Office的功能,还有很多用户有多人同时在线编辑OfficeWord文档的需求,下面介绍如何用猿大师办公助手实现多人同时在线编辑OfficeWord文档。 猿......
  • uniapp 页面导航条配置节点 navigation-bar
    navigation-bar页面导航条配置节点,用于指定导航栏的一些属性。只能是 page-meta 组件内的第一个节点,需要配合它一同使用。平台差异说明AppH5微信小程序支付宝小程序百度小程序抖音小程序、飞书小程序QQ小程序快手小程序京东小程序√2.6.3+2.6.3+√2.9.0+......
  • (开题报告)django+vue电影推荐系统APP源码+论文
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容选题背景关于电影推荐系统的研究,现有研究多集中在推荐算法的优化、单一框架的实现等方面。专门针对django+vue组合框架构建电影推荐系统APP的研......