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

相关推荐
GiantGo1 天前
一键导出PPT备注到Word
word·powerpoint·导出备注
初九之潜龙勿用1 天前
C# 操作Word模拟解析HTML标记之背景色
开发语言·c#·word·.net·office
时光追逐者1 天前
使用 MWGA 帮助 7 万行 Winforms 程序快速迁移到 WEB 前端
前端·c#·.net
老骥伏枥~1 天前
【C# 入门】程序结构与 Main 方法
开发语言·c#
全栈师1 天前
java和C#的基本语法区别
java·开发语言·c#
web打印社区1 天前
vue页面打印:printjs实现与进阶方案推荐
前端·javascript·vue.js·electron·html
钰fly1 天前
联合编程(加载单个工具,ini读写,图片读写,setting存储)
c#
FuckPatience1 天前
C# 对象初始化器对属性赋值vs构造函数里对属性赋值
c#
大三开学菜鸟1 天前
Word 字符数精确统计工具
word
骆驼爱记录1 天前
Word题注编号间距调整4种方法
自动化·word·excel·wps·新人首发