如何在用C#编写的Web-API中集成COM Interop(Excel,Ms Word等的操作)?

时间:2019-06-24 19:39:02

标签: c# .net excel api com-interop

我正在尝试将COM互操作集成到用C#编写的Web API中。而且,Web api的.net核心似乎无法支持COM技术。

这是我收到的错误消息:

FlicApi.Controllers.ButtonController.Post(string buttonId)
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

是否有任何方法可以绕过Web API的网络核心不支持COM的情况?最终,我想要实现的是调用API,并在Microsoft Excel上进行一些操作。

这是我尝试过的:

        // POST api/button/buttonId
        [HttpPost("{buttonId}")]
        public ActionResult<string> Post(string buttonId)
        {
            //Console.WriteLine(value);

            //start Excel and get Application Object
            oXL = new Excel.Application();
            oXL.Visible = true;
            //Get a new workbook.
            oWB = oXL.Workbooks.Add(Missing.Value);
            oSheet = (Excel._Worksheet)oWB.ActiveSheet;

            //Add table headers going cell by cell.
            oSheet.Cells[1, 1] = "First Name";
            oSheet.Cells[1, 2] = "Last Name";
            oSheet.Cells[1, 3] = "Full Name";
            oSheet.Cells[1, 4] = "Salary";

            oWB.SaveCopyAs(@"/Users/eaxz/Desktop/book1.xlsx");

            return "success";


        }

1 个答案:

答案 0 :(得分:0)

COM Interop对于服务器端环境不是一个很好的选择。您可以尝试一些第三方组件,例如GrapeCiy Document API