学习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

相关推荐
lzhdim3 分钟前
SharpCompress:跨平台的 C# 压缩与解压库
开发语言·c#
~plus~2 小时前
.NET 8 C# 委托与事件实战教程
网络·c#·.net·.net 8·委托与事件·c#进阶
beyond谚语3 小时前
接口&抽象类
c#·接口隔离原则·抽象类
新手小新3 小时前
C#学习笔记1-在VS CODE部署C#开发环境
笔记·学习·c#
阿捞24 小时前
Inertia.js 持久布局实现原理
前端·javascript·html
rockey6276 小时前
AScript动态脚本多语言环境支持
sql·c#·.net·script·eval·function·动态脚本
ou.cs7 小时前
c# SemaphoreSlim保姆级教程
开发语言·网络·c#
龙侠九重天7 小时前
ML.NET 实战:快速构建分类模型
分类·数据挖掘·c#·.net
伟贤AI之路7 小时前
为什么AI里的公式复制到Word格式会乱?
人工智能·word·latex
你挚爱的强哥8 小时前
欺骗加载进度条,应用于无法监听接口数据传输进度的情况
前端·javascript·html