欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2017年11月24日 10:05:15   作者:begrateful  
這篇文章主要給大家介紹了關(guān)于利用C#代碼將html樣式文件與Word文檔互換的方法,文中通過示例代碼將兩種轉(zhuǎn)換介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

一、C#代碼將html樣式文件轉(zhuǎn)為Word文檔

首先有個這樣的需求,將以下網(wǎng)頁內(nèi)容下載為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">中標(biāo)通知書<hr /></td>
  </tr>
  <tr>
  <td style="text-align: left;font-size:20px;">XX</td>
  </tr>
  <tr>
  <td style="text-align: left"> “XXXX物資平臺”ZY1703220001號標(biāo)的開標(biāo)結(jié)果為貴方中標(biāo),現(xiàn)通知如下:</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>數(shù)量(噸)</th>
  <th>中標(biāo)價格(含稅總金額:元)</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個工作日內(nèi)交齊全額貨款并簽訂合同。
  </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>

樣式展示:

第一步:封裝一個方法

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

2:根據(jù)id查詢當(dāng)前中標(biāo)信息(EF)

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

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

  3-2:布局標(biāo)簽中的樣式必須是內(nèi)聯(lián),就是寫在標(biāo)簽中,不能寫在外部.css中。

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

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

6:關(guān)鍵代碼

 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標(biāo)簽指向這個方法即可下載為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">中標(biāo)通知書<hr /></td>
  </tr>
  <tr>
  <td style="text-align: left;font-size:20px;">@BidderName</td>
  </tr>
  <tr>
  <td style="text-align: left"> “XXXX物資平臺”@ResourceCode號標(biāo)的開標(biāo)結(jié)果為貴方中標(biāo),現(xiàn)通知如下:</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>數(shù)量(@Unit)</th>
  <th>中標(biāo)價格(含稅總金額:元)</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個工作日內(nèi)交齊全額貨款并簽訂合同。
  </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>
 /// 下載中標(biāo)通知書
 /// 用法:前端一個a標(biāo)簽指向這個控制器的這個方法
 /// </summary>
 /// <param name="id">中標(biāo)通知書Id</param>
 [AbpMvcAuthorize(BiddingNoticeAppPermissions.BiddingNotice)]

 public ActionResult DownBiddingNoticeModal(long id)
 {
  #region 讀取模板 
  var html = GetBidTempStrng();
  #endregion

  #region 根據(jù)ID讀取中標(biāo)內(nèi)容 替換數(shù)據(jù)
  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 轉(zhuǎn)換為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", $"中標(biāo)通知書.doc");

  #endregion
 }

 /// <summary>
 /// 讀取中標(biāo)通知書模板
 /// </summary>
 /// <returns></returns>
 private string GetBidTempStrng()
 {
  StringBuilder sbHtml = new StringBuilder();
  // 讀取模板替換數(shù)據(jù)
  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文檔轉(zhuǎn)換為HTML

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

頁面代碼:

<span style="font-size:18px;"><div> 
<input id="File1" type="file" runat="server"/> 
<asp:Button ID="btnConvert" runat="server" Text="轉(zhuǎn)換" 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轉(zhuǎn)換為Html 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void btnConvert_Click(object sender, EventArgs e) 
{ 
try 
{ 

//上傳 
//uploadWord(File1); 
//轉(zhuǎn)換 
wordToHtml(File1); 
} 
catch (Exception ex) 
{ 
throw ex; 
} 
finally 
{ 
Response.Write("恭喜,轉(zhuǎn)換成功!"); 
} 

} 

//上傳文件并轉(zhuǎn)換為html wordToHtml(wordFilePath) 
///<summary> 
///上傳文件并轉(zhuǎn)存為html 
///</summary> 
///<param name="wordFilePath">word文檔在客戶機(jī)的位置</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(); 

//應(yīng)當(dāng)先把文件上傳至服務(wù)器然后再解析文件為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 }); 

// 轉(zhuǎn)換格式,另存為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(); 

// 判斷指定目錄下是否存在文件夾,如果不存在,則創(chuàng)建 
if (!Directory.Exists(Server.MapPath("~\\html"))) 
{ 
// 創(chuàng)建up文件夾 
Directory.CreateDirectory(Server.MapPath("~\\html")); 
} 

//被轉(zhuǎn)換的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 }); 

//關(guān)閉文檔 
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); 
//轉(zhuǎn)到新生成的頁面 
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(); 

// 判斷指定目錄下是否存在文件夾,如果不存在,則創(chuàng)建 
if (!Directory.Exists(Server.MapPath("~\\wordTmp"))) 
{ 
// 創(chuàng)建up文件夾 
Directory.CreateDirectory(Server.MapPath("~\\wordTmp")); 
} 

//上傳路徑 指當(dāng)前上傳頁面的同一級的目錄下面的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> 

效果圖:

轉(zhuǎn)換后的Html文件


這樣就可以簡單的在Html中展示word文檔中的內(nèi)容,而不需要在自己進(jìn)行編輯了。當(dāng)然,如果有需要的話,可以將轉(zhuǎn)換的Html的路徑存入數(shù)據(jù)庫,根據(jù)不同的條件直接進(jìn)行訪問。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。   

相關(guān)文章

最新評論