学习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);
}

参考文献:

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

相关推荐
web打印社区8 小时前
网页静默打印热敏小票:从 HTML 到出纸的完整指南
前端·javascript·vue.js·electron·pdf·html
JustCheng18 小时前
Dispacher(1/2)深入解析-详细使用
c#
用户298698530141 天前
React 中 HTML 内容转 Word 文档的实现方案
javascript·react.js·html
CoderIsArt1 天前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
XLYcmy2 天前
HTML/CSS/JS 基础与 Vue 技术栈深度解析
java·前端·css·html·vue3·vue2·api
呆呆敲代码的小Y2 天前
【游戏开发】Lua 与 C# 交互原理解析
c#·lua·交互·热更新·lua与c#交互·游戏热更新
用户298698530142 天前
PDF 转纯文本(TXT)免费攻略:轻松提取文字内容
人工智能·后端·c#
呆呆敲代码的小Y2 天前
【游戏开发】C# 中的迭代器
java·开发语言·c#·迭代器
晴天162 天前
HTML canvas标签使用指南-Day32
前端·html