成都创新互联网站制作重庆分公司

利用C#代码将html样式文件与Word文档互换的方法

一、C#代码将html样式文件转为Word文档

创新互联公司是一家专业提供隰县企业网站建设,专注与成都网站建设、网站建设、H5高端网站建设、小程序制作等业务。10年已为隰县众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。

首先有个这样的需求,将以下网页内容下载为Word文件。

html代码:

样式展示:

利用C#代码将html样式文件与Word文档互换的方法

第一步:封装一个方法

1:在控制器BiddingNoticeManageController创建一个DownBiddingNoticeModal方法。(采用的MVC模式)

2:根据id查询当前中标信息(EF)

3:建一个中标通知书的html模板页(数据字段自定义占位符)

3-1:注:html模板中不需要、、、<body>等标签。只是单纯的div布局标签</p><p>3-2:布局标签中的样式必须是内联,就是写在标签中,不能写在外部.css中。</p><p>4:通过Stream、StreamReader两个类来读取这个模板文件(返回的是html字符串)。</p><p>5:2中查询出数据(对应字段)替换4中返回的html字符串中的占位符。</p><p>6:关键代码</p><div><pre> StringBuilder sb = new StringBuilder(); sb.Append( "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns = \"http://www.w3.org/TR/REC-html40\">"); sb.Append(html); sb.Append("</html>");</pre></div><p>7:用法:在页面前端写一个a标签指向这个方法即可下载为Word文件了。</p><p>HTML模板文件:</p><div><pre><div class="modal-body"> <div > <table > <tr> <td >中标通知书<hr /></td> </tr> <tr> <td >@BidderName</td> </tr> <tr> <td > “XXXX物资平台”@ResourceCode号标的开标结果为贵方中标,现通知如下:</td> </tr> </table> <table border="1" cellspacing="0" cellpadding="10" > <tr > <th>品名</th> <th>资源编号</th> <th>数量(@Unit)</th> <th>中标价格(含税总金额:元)</th> <th>钢厂</th> <th>存放地(提货地)</th> </tr> <tr > <td>@ResourceName</td> <td>@ResourceCode</td> <td>@Count</td> <td>@TenderPrice</td> <td>@BrandName</td> <td>@InventoryPlace</td> </tr> <tr> <td colspan="6">备注:@Remarks</td> </tr> </table> <table > <tr> <td > 请贵方在收到通知书的5个工作日内交齐全额货款并签订合同。 </td> </tr> <tr> <td > 特此通知。 </td> </tr> <tr> <td > XXXX物资平台 </td> </tr> <tr> <td > @Year 年 @Moth 月 @Day 日 </td> </tr> </table> </div> </div></pre></div><div><pre> /// <summary> /// 下载中标通知书 /// 用法:前端一个a标签指向这个控制器的这个方法 /// </summary> /// <param name="id">中标通知书Id</param> [AbpMvcAuthorize(BiddingNoticeAppPermissions.BiddingNotice)] public ActionResult DownBiddingNoticeModal(long id) { #region 读取模板 var html = GetBidTempStrng(); #endregion #region 根据ID读取中标内容 替换数据 var model = _biddingNoticeRepository.FirstOrDefault(id); if (model != null) { html = html.Replace("@BrandName", model.BrandName).Replace("@ResourceCode", model.ResourceCode) .Replace("@ResourceName", model.ResourceName).Replace("@Count", model.Count.ToString()) .Replace("@TenderPrice", model.TenderPrice.ToString()).Replace("@BidderName", model.BidderName) .Replace("@InventoryPlace", model.InventoryPlace).Replace("@Remarks", model.Remarks) .Replace("@Year", model.CreationTime.Year.ToString()).Replace("@Moth", model.CreationTime.Month.ToString()) .Replace("@Day", model.CreationTime.Day.ToString()).Replace("@Unit", model.Unit); } else { html = html.Replace("@BrandName", "XXXXX").Replace("@ResourceCode", "ZYXXXXXXXX") .Replace("@ResourceName", "XXXXX").Replace("@Count", "0") .Replace("@TenderPrice", "0").Replace("@BidderName", "XXXXX") .Replace("@InventoryPlace", "XXXXX").Replace("@Remarks", "XXXXXXXX") .Replace("@Year", "XXXX").Replace("@Moth", "XX") .Replace("@Day", "XX").Replace("@Unit", "X"); } #endregion #region 转换为Word文档样式 StringBuilder sb = new StringBuilder(); sb.Append( "<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns = \"http://www.w3.org/TR/REC-html40\">"); sb.Append(html); sb.Append("</html>"); return File(Encoding.UTF8.GetBytes(sb.ToString()), "application/msword", $"中标通知书.doc"); #endregion } /// <summary> /// 读取中标通知书模板 /// </summary> /// <returns></returns> private string GetBidTempStrng() { StringBuilder sbHtml = new StringBuilder(); // 读取模板替换数据 var path = Server.MapPath("~/Common/BidTemplace/BidTemp.html"); using (Stream inStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) using (StreamReader outStream = new StreamReader(inStream, Encoding.Default)) { while (!outStream.EndOfStream) { sbHtml.Append(outStream.ReadLine()); } } var html = sbHtml.ToString(); return html; }</pre></div><p><strong>二、C# 将Word文档转换为HTML</strong></p><p>日常生活中,我们总是在Word中进行文字的编辑,它不仅能够保存Text文本,还可以保存文本的格式等等。那么如果我要将一Word文档上的内容展示在网页上,该怎么做呢?这里我提供了一个小工具,你可以将Word转换为Html,需要显示的话,可以直接访问该Html,废话不多说,下面看代码。</p><p>页面代码:</p><div><pre><span ><div> <input id="File1" type="file" runat="server"/> <asp:Button ID="btnConvert" runat="server" Text="转换" OnClick="btnConvert_Click" /> </div></span> </pre></div><p>C#代码:</p><div><pre><span deep="5">using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 将word转换为Html /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnConvert_Click(object sender, EventArgs e) { try { //上传 //uploadWord(File1); //转换 wordToHtml(File1); } catch (Exception ex) { throw ex; } finally { Response.Write("恭喜,转换成功!"); } } //上传文件并转换为html wordToHtml(wordFilePath) ///<summary> ///上传文件并转存为html ///</summary> ///<param name="wordFilePath">word文档在客户机的位置</param> ///<returns>上传的html文件的地址</returns> public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath) { Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = word.GetType(); Microsoft.Office.Interop.Word.Documents docs = word.Documents; // 打开文件 Type docsType = docs.GetType(); //应当先把文件上传至<a title="服务器" target="_blank" href="http://www.cdfuwuqi.com/">服务器</a>然后再解析文件为html string filePath = uploadWord(wordFilePath); //判断是否上传文件成功 if (filePath == "0") return "0"; //判断是否为word文件 if (filePath == "1") return "1"; object fileName = filePath; Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true }); // 转换格式,另存为html Type docType = doc.GetType(); string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); // 判断指定目录下是否存在文件夹,如果不存在,则创建 if (!Directory.Exists(Server.MapPath("~\\html"))) { // 创建up文件夹 Directory.CreateDirectory(Server.MapPath("~\\html")); } //被转换的html文档保存的位置 string ConfigPath = HttpContext.Current.Server.MapPath("html/" + filename + ".html"); object saveFileName = ConfigPath; /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成: * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, * null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML}); * 其它格式: * wdFormatHTML * wdFormatDocument * wdFormatDOSText * wdFormatDOSTextLineBreaks * wdFormatEncodedText * wdFormatRTF * wdFormatTemplate * wdFormatText * wdFormatTextLineBreaks * wdFormatUnicodeText */ docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML }); //关闭文档 docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { null, null, null }); // 退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); //转到新生成的页面 return ("/" + filename + ".html"); } public string uploadWord(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles) { if (uploadFiles.PostedFile != null) { string fileName = uploadFiles.PostedFile.FileName; int extendNameIndex = fileName.LastIndexOf("."); string extendName = fileName.Substring(extendNameIndex); string newName = ""; try { //验证是否为word格式 if (extendName == ".doc" || extendName == ".docx") { DateTime now = DateTime.Now; newName = now.DayOfYear.ToString() + uploadFiles.PostedFile.ContentLength.ToString(); // 判断指定目录下是否存在文件夹,如果不存在,则创建 if (!Directory.Exists(Server.MapPath("~\\wordTmp"))) { // 创建up文件夹 Directory.CreateDirectory(Server.MapPath("~\\wordTmp")); } //上传路径 指当前上传页面的同一级的目录下面的wordTmp路径 uploadFiles.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("wordTmp/" + newName + extendName)); } else { return "1"; } } catch { return "0"; } //return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath + "/wordTmp/" + newName + extendName; return System.Web.HttpContext.Current.Server.MapPath("wordTmp/" + newName + extendName); } else { return "0"; } }</span> </pre></div><p>效果图:</p><p>转换后的Html文件</p><p><img src="/upload/otherpic57/98279.jpg" alt="利用C#代码将html样式文件与Word文档互换的方法"></p><p>这样就可以简单的在Html中展示word文档中的内容,而不需要在自己进行编辑了。当然,如果有需要的话,可以将转换的Html的路径存入数据库,根据不同的条件直接进行访问。</p><p><strong>总结</strong></p><p>以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对创新互联的支持。   </p> <br> 分享文章:利用C#代码将html样式文件与Word文档互换的方法 <br> 链接分享:<a href="http://cxhlcq.com/article/joojgj.html">http://cxhlcq.com/article/joojgj.html</a> </div> </div> </div> <div class="other container"> <h3>其他资讯</h3> <ul> <li> <a href="/article/hggcsc.html">安全编程go语言 编程 go</a> </li><li> <a href="/article/hggcdc.html">go语言开发者叫什么 go 开发语言</a> </li><li> <a href="/article/hggcog.html">go语言中的锁太多了 go 锁机制</a> </li><li> <a href="/article/hggcoe.html">关于Windows系统8激活的信息</a> </li><li> <a href="/article/hggdhp.html">windows工控系统的简单介绍</a> </li> </ul> </div> <div class="footer"> <div class="foota container"> <div class="foot_nav fl col-lg-8 col-md-8 col-sm-12 col-xs-12"> <ul> <li class="col-lg-3 col-md-3 col-sm-3 col-xs-6"> <h3>网站制作</h3> <a href="http://www.myzwz.com/" target="_blank">绵阳网站制作</a><a href="http://www.cdxwcx.cn/bj/" target="_blank">网站制作价格</a><a href="http://chengdu.cdcxhl.cn/qiye/" target="_blank">企业网站制作</a><a href="https://www.cdcxhl.com/mobile.html" target="_blank">手机网站制作</a><a href="https://www.cdcxhl.com/zhizuo/chengdu.html" target="_blank">四川成都网站制作</a><a href="http://m.xwcx.net/" target="_blank">H5网站制作</a> </li> <li class="col-lg-3 col-md-3 col-sm-3 col-xs-6"> <h3>企业服务</h3> <a href="https://www.cdcxhl.com/shoulu/" target="_blank">网站收录</a><a href="https://www.cdcxhl.com/service/zzgj.html" target="_blank">备案资质管家服务</a><a href="https://www.cdcxhl.com/ruanwen/yingxiao/" target="_blank">软文发布平台</a><a href="https://www.cdcxhl.com/shoulu/" target="_blank">网站免费收录</a><a href="https://www.cdcxhl.com/ruanwen/yingxiao/" target="_blank">软文推广</a><a href="https://www.cdcxhl.com/weihu/chengdu.html" target="_blank">成都网站维护</a> </li> <li class="col-lg-3 col-md-3 col-sm-3 col-xs-6"> <h3>网站建设</h3> <a href="http://www.lzwzjz.cn/" target="_blank">泸州网站建设</a><a href="https://www.cdcxhl.com/shop.html" target="_blank">商城网站建设</a><a href="http://www.scgulin.cn/" target="_blank">古蔺网站建设</a><a href="http://www.cxjianzhan.cn/" target="_blank">网站建设开发</a><a href="http://m.xwcx.net/wangzhan/" target="_blank">成都定制高级网站建设</a><a href="http://chengdu.kswjz.com/" target="_blank">成都网站建设</a> </li> <li class="col-lg-3 col-md-3 col-sm-3 col-xs-6"> <h3>服务器托管</h3> <a href="https://www.xwcx.net/tgxq/cdghjf.html" target="_blank">成都光华机房</a><a href="https://www.cdcxhl.com/idc/yldx.html" target="_blank">义龙电信机房</a><a href="https://www.cdcxhl.com/cqtuoguan.html" target="_blank">重庆服务器托管</a><a href="https://www.cdcxhl.com/tuoguan/zongshu/" target="_blank">成都棕树机房</a><a href="https://www.cdcxhl.com/idc/meishan.html" target="_blank">眉山服务器托管</a><a href="https://www.cdcxhl.com/idc/cqstsx.html" target="_blank">重庆水土双线托管</a> </li> </ul> </div> <div class="footar fl col-lg-4 col-md-4 col-sm-12 col-xs-12"> <p>全国免费咨询:</p> <b>400-028-6601</b> <p>业务咨询:028-86922220 / 13518219792</p> <p>节假值班:18980820575 / 13518219792</p> <p>联系地址:成都市太升南路288号锦天国际A幢1002号</p> </div> </div> <div class="footb"> <div class="copy container"> <div class="fl">Copyright © 成都创新互联科技有限公司重庆分公司 <a href="https://beian.miit.gov.cn/" target="_blank">渝ICP备2021005571号</a></div> <!--<div class="fr"><a href="https://www.cdxwcx.com/" target="_blank">成都网站建设</a>:<a href="https://www.cdcxhl.com/" target="_blank">创新互联</a></div>--> </div> </div> <div class="link"> <div class="container"> 友情链接:: <a href="https://www.cdcxhl.com/" target="_blank">成都网站建设</a> <a href="https://www.cdcxhl.com/city/chongqing.html" target="_blank">重庆网站建设</a> <a href="">四川网站建设</a> <a href="">重庆建设网站</a> <a href="https://www.cdxwcx.com/jifang/xiyun.html" target="_blank">移动服务器托管</a> <a href="http://www.cdfuwuqi.com/" target="_blank">成都服务器托管</a> <a href="https://www.cdcxhl.cn/" target="_blank">云服务器</a> <a href="http://www.cdhuace.com/" target="_blank">广告设计制作</a> <a href="https://www.cdcxhl.com/sheji/chongqing.html" target="_blank">重庆网页设计</a> <a href="https://www.cdcxhl.com/zuo/chongqing.html" target="_blank">重庆做网站</a> <a href="https://www.cdcxhl.com/zhizuo/chongqing.html" target="_blank">重庆网站制作</a> <a href="">重庆网站建设</a> <a href="">重庆网站公司</a> <a href="">渝中网站制作</a> <a href="">重庆网站设计</a> </div> </div> </div> <div class="foot"> <ul class="public-celan"> <li> <a href="https://p.qiao.baidu.com/cps3/chatIndex?siteToken=6ce441ff9e2d6bedbdfc2a4138de449e&speedLogId=162260383240185e3_1622603832401_02407&eid=6256368&reqParam=%7B%22from%22%3A1%2C%22sessionid%22%3A%22-100%22%2C%22siteId%22%3A%2211284691%22%2C%22tid%22%3A%22-1%22%2C%22userId%22%3A%226256368%22%2C%22ttype%22%3A1%2C%22pageId%22%3A0%7D" target="_blank" class="a1 db tc"> <img src="/Public/Home/img/icon-23.png" alt="" class="db auto"> <span class="span-txt">在线咨询</span> </a> </li> <li> <a href="tel:18980820575" class="a1 db tc"> <img src="/Public/Home/img/icon-24.png" alt="" class="db auto"> <span class="span-txt">电话咨询</span> </a> </li> <li> <a target="_blank" href="tencent://message/?uin=1683211881&Site=&Menu=yes" class="a1 db tc"> <img src="/Public/Home/img/icon-25.png" alt="" class="db auto"> <span class="span-txt">QQ咨询</span> </a> </li> <li> <a target="_blank" href="tencent://message/?uin=532337155&Site=&Menu=yes" class="a1 db tc public-yuyue-up"> <img src="/Public/Home/img/icon-26.png" alt="" class="db auto"> <span class="span-txt">预约顾问</span> </a> </li> </ul> </div> <div class="customer"> <dl class="icon1"> <dt> <a href="tencent://message/?uin=1683211881&Site=&Menu=yes"> <i class="iconT"><img src="/Public/Home/img/QQ.png" alt=""></i> <p>在线咨询</p> </a> </dt> </dl> <dl class="icon2"> <dt><i><img src="/Public/Home/img/weixin.png" alt=""></i><p>微信咨询</p></dt> <dd><img src="/Public/Home/img/ewm.png"></dd> </dl> <dl class="icon3"> <dt><i><img src="/Public/Home/img/dianhua.png" alt=""></i><p>电话咨询</p></dt> <dd> <p>028-86922220(工作日)</p> <p>18980820575(7×24)</p> </dd> </dl> <dl class="icon4"> <dt class="sShow"> <a href="tencent://message/?uin=244261566&Site=&Menu=yes"> <i><img src="/Public/Home/img/dengji.png" alt=""></i><p>提交需求</p> </a> </dt> </dl> <dl class="icon5"> <dt class="gotop"> <a href="#top"> <i><img src="/Public/Home/img/top.png" alt=""></i><p>返回顶部</p> </a> </dt> </dl> </div> </body> </html> <script> $(".con img").each(function(){ var src = $(this).attr("src"); //获取图片地址 var str=new RegExp("http"); var result=str.test(src); if(result==false){ var url = "https://www.cdcxhl.com"+src; //绝对路径 $(this).attr("src",url); } }); window.onload=function(){ document.oncontextmenu=function(){ return false; } } </script>