重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

利用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://cqcxhl.com/article/joojgj.html">http://cqcxhl.com/article/joojgj.html</a> </div> </div> <div class="other"> <h3>其他资讯</h3> <ul> <li> <a href="/article/gjeeip.html">计算机网络中如何在不增加外链与新内容的情况下提高网站流量</a> </li><li> <a href="/article/gjeesc.html">Python如何实现线性规划</a> </li><li> <a href="/article/gjeeei.html">MySQL中的索引是什么</a> </li><li> <a href="/article/gjeech.html">解决anacondapip用不了的方法</a> </li><li> <a href="/article/gjeshc.html">SpringBootControllerPost接口单元测试示例</a> </li> </ul> </div> </div> <div class="footer"> <div class="footer_content"> <div class="footer_content_top clear"> <div class="content_top_share fl"> <div><img src="/Public/Home/img/logo.png"></div> <div class="top_share_content"> <dd>分享至:</dd> <dt class="bdsharebuttonbox clear" id="share"> <a href="#" class="bds_tsina iconfont fl" data-cmd="tsina" title="分享到新浪微博"></a> <a href="#" class="bds_sqq iconfont fl" data-cmd="sqq" title="分享到QQ好友"></a> <a href="#" class="bds_weixin iconfont fl" data-cmd="weixin" title="分享到微信"></a> <a href="#" class="bds_weixin iconfont fl" data-cmd="tieba" title="分享到贴吧"></a> </dt> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> </div> </div> <div class="content_top_left fl clear"> <div class="top_left_list fl"> <dd><a href="/about/">关于我们</a></dd> <dt> <a href="/about/#gsjj">公司简介</a> <a href="/about/#fzlc">发展历程</a> </dt> </div> <div class="top_left_list fl"> <dd><a href="/service/">服务项目</a></dd> <dt> <a href="/service/">高端网站建设</a> <a href="/miniprogram/">小程序开发</a> <a href="/service/app.html">APP开发</a> <a href="/service/yingxiao.html">网络营销</a> </dt> </div> <div class="top_left_list fl"> <dd><a href="/jianzhan/">建站知识</a></dd> <dt> <a href="/jianzhan/2.html">网站建设</a> <a href="/jianzhan/3.html">网站设计</a> <a href="/jianzhan/4.html">网站制作</a> <a href="/jianzhan/5.html">小程序</a> </dt> </div> <div class="top_left_list fl"> <dd><a href="/contact/">联系我们</a></dd> <dt> <a href="/contact/#lxwm">公司地址</a> <a href="/contact/#rczp">人才招聘</a> </dt> </div> </div> <div class="content_top_right addressR fr"> <div class="top_right_title addressf_title"> <a href="javascript:;" class="on">成都</a> <a href="javascript:;">重庆</a> </div> <div class="top_right_content addressf"> <div class="right_content_li on"> <div class="right_content_list clear"> <dd class="fl iconfont"></dd> <dt class="fl">电话:028-86922220</dt> </div> <div class="right_content_list clear"> <dd class="fl iconfont"></dd> <dt class="fl">地址:成都市太升南路288号锦天国际A幢1002号</dt> </div> </div> <div class="right_content_li"> <div class="right_content_list clear"> <dd class="fl iconfont"></dd> <dt class="fl">电话:028-86922220</dt> </div> <div class="right_content_list clear"> <dd class="fl iconfont"></dd> <dt class="fl">地址:重庆市南岸区弹子石腾龙大道58号2栋21-6</dt> </div> </div> </div> </div> </div> </div> <div class="footer_content_copyright clear">版权所有:成都创新互联科技有限公司重庆分公司 <a href="http://beian.miit.gov.cn/" rel="nofollow" target="_blank">渝ICP备2021005571号-4</a> </div> </div> <!--浮窗--> <div class="FloatingWindow clear"> <a href="tencent://message/?uin=1683211881&Site=&Menu=yes" class="FloatingWindow_list fr"> <div class="FloatingWindow_list_title"> <dd class="iconfont"></dd> <dt><span>在线</span>咨询</dt> </div> </a> <a href="javascript:;" class="FloatingWindow_list fr"> <div class="FloatingWindow_list_title"> <dd class="iconfont"></dd> <dt>服务热线</dt> </div> <div class="FloatingWindow_list_down fadeInRight animated">服务热线:028-86922220</div> </a> <a href="javascript:;" class="FloatingWindow_list fr STop"> <div class="FloatingWindow_list_title"> <dd class="iconfont"></dd> <dt>TOP</dt> </div> </a> </div> <script src="/Public/Home/js/jquery-1.8.3.min.js"></script> <script src="/Public/Home/js/comm.js"></script> <script src="/Public/Home/js/wow.js"></script> <script src="/Public/Home/js/common.js"></script> </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); } }); </script>