You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7.0使用Microsoft.Office.Interop.Word报错:COM不受支持

解决.NET 7中使用Microsoft.Office.Interop.Word的COM不支持错误

错误原因

Microsoft.Office.Interop.Word依赖COM组件运行,而.NET 7作为跨平台框架,默认不支持COM交互(即使Windows环境下也不推荐使用Interop,因为它强依赖本地安装的Office,存在版本兼容、进程残留等问题),所以会抛出System.PlatformNotSupportedException: COM is not supported。

替代方案

推荐使用无需依赖Office的开源/官方库来处理Word文档:

方案1:使用微软官方OpenXML SDK

OpenXML是微软针对Office开放格式(.docx/.xlsx等)的官方处理库,无需安装Office,跨平台支持良好。

  1. 安装NuGet包:
Install-Package DocumentFormat.OpenXml
  1. 提取文本的示例代码:
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

static string GetTextFromWord(string filePath)
{
    StringBuilder textBuilder = new StringBuilder();
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
    {
        Body body = wordDoc.MainDocumentPart.Document.Body;
        foreach (var element in body.Descendants<Text>())
        {
            textBuilder.Append(element.Text);
        }
    }
    return textBuilder.ToString();
}

// 调用示例
string text = GetTextFromWord(@"D:\Articles2.docx");
Console.WriteLine(text);

方案2:使用DocX库(更简洁易用)

DocX是基于OpenXML封装的第三方库,API更友好,代码更简洁。

  1. 安装NuGet包:
Install-Package DocX
  1. 提取文本的示例代码:
using System.Text;
using Novacode;

static string GetTextFromWord(string filePath)
{
    using (DocX document = DocX.Load(filePath))
    {
        return document.Text;
    }
}

// 调用示例
string text = GetTextFromWord(@"D:\Articles2.docx");
Console.WriteLine(text);

注意事项

  • 避免再使用Microsoft.Office.Interop.Word,除了COM支持问题,它还需要目标机器安装对应版本的Office,服务器环境几乎无法满足,且容易导致Word进程残留无法关闭。
  • 上述两种方案均支持.NET 7及以上版本,跨平台(Windows/Linux/macOS)可用。

内容的提问来源于stack exchange,提问作者Pati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:46:03