Asp.Net在线预览Word文档的解决方案与思路
前几天有个老项目找到我,有多老呢?比我工作年限都长,见到这个项目我还得叫一声前辈。
这个项目目前使用非常稳定,十多年了没怎么更新过,现在客户想加一个小功能:在线预览Word文档
。
首先想到的是用第三方的服务,例如WPS
的开放平台。
刚看完文档,客户来了句,要一次性的哦,后续再付费的通通不要。
得嘞,换其他方案吧。
项目特点
Asp.Net
不带Core
,.NET Framework 4.0
,部署在Windows
平台上。
解决方案
大致思路:先将Word
文档转换Html
,再预览Html
。
1、Word
文档转Html
先引用Office
的DLL
,在COM
里面,注意:电脑需要安装Office哦。
又注意:请在DLL
属性里面将嵌入互操作类型改为False
转换过程一个方法搞定:
using Microsoft.Office.Interop.Word;
public static string WordToHtml(string path)
{
string root = AppDomain.CurrentDomain.BaseDirectory;
var htmlName = $"{Guid.NewGuid().ToString("N")}.html";
var htmlPath = root + $"Resource/Temporary/";
if (!Directory.Exists(htmlPath))
{
Directory.CreateDirectory(htmlPath);
}
ApplicationClass word = new ApplicationClass();
Type wordType = word.GetType();
Documents docs = word.Documents;
Type docsType = docs.GetType();
Document doc = (Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });
Type docType = doc.GetType();
docType.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, doc, new object[] { (htmlPath + htmlName), WdSaveFormat.wdFormatFilteredHTML });
docType.InvokeMember("Close", BindingFlags.InvokeMethod, null, doc, null);
wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);
return htmlName;
}
2、预览
上一步Word
转Html
的方法已经准备就绪,我们再准备这样一个Word
文档。
简单写一下逻辑:
是不是特别简单,我们再看看成品效果。
这种方案局限性比较大,部署平台必须安装Office
,刚好客户能满足。
放这里分享一下,抛砖引玉,如果大家有更好的方案请不吝赐教。
转 https://www.cnblogs.com/cool-net/p/16191068.html
标签:
.net core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)