word转html方法

在网上看了一篇关于word转html的文章,感觉不错,和大家分享一下。

复制代码
 1      /// <summary> 
 2         /// word转成html 
 3         /// </summary> 
 4         /// <param name="wordfilename">word文件路径</param> 
 5         private string ConvertWordToHtml(object wordfilename)
 6         {
 7             //在此处放置用户代码以初始化页面 
 8             word.ApplicationClass word = new word.ApplicationClass();
 9             Type wordtype = word.GetType();
10             word.Documents docs = word.Documents;
11             //打开文件 
12             Type docstype = docs.GetType();
13             word.Document doc = (word.Document)docstype.InvokeMember("open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new object[] { wordfilename, true, true });
14             //转换格式,另存为 
15             Type doctype = doc.GetType();
16             string wordsavefilename = wordfilename.ToString();
17             string strsavefilename = wordsavefilename.Substring(0, wordsavefilename.Length - 3) + "html";
18             object savefilename = (object)strsavefilename;
19             doctype.InvokeMember("saveas", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { savefilename, WdSaveFormat.wdFormatFilteredHTML });
20             doctype.InvokeMember("close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
21             //退出 word 
22             wordtype.InvokeMember("quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
23             return savefilename.ToString();
24         }
word转html方法
复制代码

在此之前需要做一些准备工作

1、必须有office组件。

2、添加引用如下:

复制代码
 1   using System;
 2   using System.Collections;
 3   using System.Configuration;
 4   using System.Data;
 5   using System.Web;
 6   using System.Web.Security;
 7   using System.Web.UI;
 8   using System.Web.UI.HtmlControls;
 9   using System.Web.UI.WebControls;
10   using System.Web.UI.WebControls.WebParts;
11   using word = Microsoft.Office.Interop.Word;
12   using Microsoft.Office.Interop.Word;
页面引用命名空间
复制代码

3、项目添加Microsoft.Office.Interop.Word引用。

4、如果代码  word.ApplicationClass word = new word.ApplicationClass();提示无法嵌入互操作类型,则右键点击Microsoft.Office.Interop.Word组件选择属性,将嵌入互操作类型改为False即可解决问题。

完成之后,在word文件所在文件夹中会出现同名的html文件。但是有一个缺点,就是word排版格式不能保存。稍后改进。

posted @   竹林溪风  阅读(989)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示