国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

利用C#代碼將html樣式文件與Word文檔互換的方法

2019-10-29 21:07:37
字體:
來源:轉載
供稿:網友

一、C#代碼將html樣式文件轉為Word文檔

首先有個這樣的需求,將以下網頁內容下載為Word文件。

html代碼:

<div class="modal-body"> <div style="height:600px;width:550px; margin:0 auto;"> <table style="border-collapse:separate;border-spacing:10px;width: 100%">  <tr>  <td style="text-align: center;font-size: 30px;font-weight: bold">中標通知書<hr /></td>  </tr>  <tr>  <td style="text-align: left;font-size:20px;">XX</td>  </tr>  <tr>  <td style="text-align: left"> “XXXX物資平臺”ZY1703220001號標的開標結果為貴方中標,現通知如下:</td>  </tr> </table> <table border="1" cellspacing="0" cellpadding="10" style="border-collapse:separate;height: 300px;">  <tr style="text-align:center;">  <th>品名</th>  <th>資源編號</th>  <th>數量(噸)</th>  <th>中標價格(含稅總金額:元)</th>  <th>鋼廠</th>  <th>存放地(提貨地)</th>  </tr>  <tr style="text-align:center;">  <td>冷軋窄帶</td>  <td>ZY1703220001</td>  <td>25.725</td>  <td>47500.00</td>  <td>XX</td>  <td>XXXXXX</td>  </tr>  <tr>  <td colspan="6">備注:XXXXXX</td>  </tr> </table> <table style="border-collapse:separate;border-spacing:10px;width: 100%">  <tr>  <td style="text-align: left">   請貴方在收到通知書的5個工作日內交齊全額貨款并簽訂合同。  </td>  </tr>  <tr>  <td style="text-align: left">   特此通知。  </td>  </tr>  <tr>  <td style="text-align: right">   XXXX物資平臺  </td>  </tr>  <tr>  <td style="text-align:right">   2017 年 4月 16 日  </td>  </tr> </table> </div></div>

樣式展示:

html轉換為word文檔,html轉換成word,如何將html轉換成word

第一步:封裝一個方法

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

2:根據id查詢當前中標信息(EF)

3:建一個中標通知書的html模板頁(數據字段自定義占位符)

  3-1:注:html模板中不需要<html>、<head>、<title>、<body>等標簽。只是單純的div布局標簽

  3-2:布局標簽中的樣式必須是內聯,就是寫在標簽中,不能寫在外部.css中。

4:通過Stream、StreamReader兩個類來讀取這個模板文件(返回的是html字符串)。

5:2中查詢出數據(對應字段)替換4中返回的html字符串中的占位符。

6:關鍵代碼

 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>");

7:用法:在頁面前端寫一個a標簽指向這個方法即可下載為Word文件了。

HTML模板文件:

<div class="modal-body"> <div style="height:600px;width:550px; margin:0 auto;"> <table style="border-collapse:separate;border-spacing:10px;width: 100%">  <tr>  <td style="text-align: center;font-size: 30px;font-weight: bold">中標通知書<hr /></td>  </tr>  <tr>  <td style="text-align: left;font-size:20px;">@BidderName</td>  </tr>  <tr>  <td style="text-align: left"> “XXXX物資平臺”@ResourceCode號標的開標結果為貴方中標,現通知如下:</td>  </tr> </table> <table border="1" cellspacing="0" cellpadding="10" style="border-collapse:separate;height: 300px;">  <tr style="text-align:center;">  <th>品名</th>  <th>資源編號</th>  <th>數量(@Unit)</th>  <th>中標價格(含稅總金額:元)</th>  <th>鋼廠</th>  <th>存放地(提貨地)</th>  </tr>  <tr style="text-align:center;">  <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 style="border-collapse:separate;border-spacing:10px;width: 100%">  <tr>  <td style="text-align: left">   請貴方在收到通知書的5個工作日內交齊全額貨款并簽訂合同。  </td>  </tr>  <tr>  <td style="text-align: left">   特此通知。  </td>  </tr>  <tr>  <td style="text-align: right">   XXXX物資平臺  </td>  </tr>  <tr>  <td style="text-align:right">   @Year 年 @Moth 月 @Day 日  </td>  </tr> </table> </div></div>
 /// <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; }

二、C# 將Word文檔轉換為HTML

日常生活中,我們總是在Word中進行文字的編輯,它不僅能夠保存Text文本,還可以保存文本的格式等等。那么如果我要將一Word文檔上的內容展示在網頁上,該怎么做呢?這里我提供了一個小工具,你可以將Word轉換為Html,需要顯示的話,可以直接訪問該Html,廢話不多說,下面看代碼。

頁面代碼:

<span style="font-size:18px;"><div> <input id="File1" type="file" runat="server"/> <asp:Button ID="btnConvert" runat="server" Text="轉換" OnClick="btnConvert_Click" /> </div></span> 

C#代碼:

<span style="font-size:18px;" 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(); //應當先把文件上傳至服務器然后再解析文件為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> 

效果圖:

轉換后的Html文件

html轉換為word文檔,html轉換成word,如何將html轉換成word

這樣就可以簡單的在Html中展示word文檔中的內容,而不需要在自己進行編輯了。當然,如果有需要的話,可以將轉換的Html的路徑存入數據庫,根據不同的條件直接進行訪問。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。   


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临湘市| 内丘县| 大名县| 绥棱县| 奉贤区| 体育| 五河县| 应用必备| 浪卡子县| 温宿县| 新绛县| 东港市| 确山县| 库尔勒市| 红桥区| 鹤庆县| 英山县| 徐闻县| 绵竹市| 龙州县| 九龙城区| 宝鸡市| 赤水市| 射阳县| 江油市| 象山县| 蒙山县| 乌恰县| 邢台市| 肇庆市| 鱼台县| 秭归县| 老河口市| 城固县| 常德市| 临漳县| 肇东市| 祁东县| 德江县| 柳州市| 志丹县|