学习C#调用Microsoft.Office.Interop.Word将Word转换为html

使用微软的Microsoft.Office.Interop.Word组件也能将word转换为html,核心方法是调用Word的文档对象模型(DOM)来打开Word文档并另存为HTML格式,但这种方式需要程序所在电脑安装Microsoft Word软件,且运行程序的账户需要具有访问Word组件和文件路径的足够权限。同时确保调用Marshal.ReleaseComObject释放对象,否则可能导致Word进程无法彻底关闭,占用系统资源。
  VS2022中通过添加Com引用添加Microsoft Word Object Library组件。

  程序主要代码及转换后的html文件如下所示:

csharp 复制代码
using Microsoft.Office.Interop.Word;

string inputFilePath = "测试输出文件.docx";
string outputFilePath = "testdoc.html";

Application wordApp = new Application();
Document wordDoc = null;

try
{    
    wordDoc = wordApp.Documents.Open(inputFilePath);
    
    //wdFormatFilteredHTML格式去除了Word特有标签和样式,如果需要完整保留所有Word信息,
    //应设置为wdFormatHTML
    WdSaveFormat saveFormat = WdSaveFormat.wdFormatFilteredHTML;
    wordDoc.SaveAs2(outputFilePath, saveFormat);
}
catch (Exception ex)
{    
    Console.WriteLine($"转换过程中出现错误: {ex.Message}");
    throw;
}
finally
{
    if (wordDoc != null)
    {
        wordDoc.Close(false);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
    }
    wordApp.Quit(false);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}

参考文献:

1\]https://blog.csdn.net/x1234w4321/article/details/140326650

相关推荐
咖啡の猫1 天前
Python字典的查询操作
数据库·python·c#
czhc11400756631 天前
c# 1213
开发语言·数据库·c#
xiaoid1 天前
C#向jave平台的API接口推送
c#·post·webapi
小猪快跑爱摄影1 天前
【AutoCad 2025】【C#】零基础教程(三)——获取选中的 Entity 插件 =》 初识 Entity 派生类
c#·autocad
czhc11400756631 天前
c#w 1214
开发语言·c#
用户298698530141 天前
C# 中如何从 URL 下载 Word 文档:基于 Spire.Doc 的高效解决方案
后端·c#·.net
xhxxx1 天前
别再被 CSS 定位搞晕了!5 种 position 一图打尽 + 实战代码全公开
前端·css·html
wangbing11251 天前
将swagger在线文档转为word
microsoft·c#·word
mangge081 天前
定时刷新已经登录过的网页c#
c#
询问QQ688238861 天前
基于偏最小二乘算法(PLS)的多输出数据回归预测
html