利用C#代碼將html樣式文件與Word文檔互換的方法
一、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">中標通知書<hr /></td> </tr> <tr> <td style="text-align: left;font-size:20px;">XX</td> </tr> <tr> <td style="text-align: left"> “XXXX物資平臺”ZY1703220001號標的開標結(jié)果為貴方中標,現(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>中標價格(含稅總金額:元)</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查詢當前中標信息(EF)
3:建一個中標通知書的html模板頁(數(shù)據(jù)字段自定義占位符)
3-1:注:html模板中不需要<html>、<head>、<title>、<body>等標簽。只是單純的div布局標簽
3-2:布局標簽中的樣式必須是內(nèi)聯(lián),就是寫在標簽中,不能寫在外部.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標簽指向這個方法即可下載為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號標的開標結(jié)果為貴方中標,現(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>中標價格(含稅總金額:元)</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>
/// 下載中標通知書
/// 用法:前端一個a標簽指向這個控制器的這個方法
/// </summary>
/// <param name="id">中標通知書Id</param>
[AbpMvcAuthorize(BiddingNoticeAppPermissions.BiddingNotice)]
public ActionResult DownBiddingNoticeModal(long id)
{
#region 讀取模板
var html = GetBidTempStrng();
#endregion
#region 根據(jù)ID讀取中標內(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", $"中標通知書.doc");
#endregion
}
/// <summary>
/// 讀取中標通知書模板
/// </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中進行文字的編輯,它不僅能夠保存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文檔在客戶機的位置</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)當先把文件上傳至服務(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"));
}
//上傳路徑 指當前上傳頁面的同一級的目錄下面的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)容,而不需要在自己進行編輯了。當然,如果有需要的話,可以將轉(zhuǎn)換的Html的路徑存入數(shù)據(jù)庫,根據(jù)不同的條件直接進行訪問。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
c#使用DotNetZip封裝類操作zip文件(創(chuàng)建/讀取/更新)實例
DotnetZip是一個開源類庫,支持.NET的任何語言,可很方便的創(chuàng)建,讀取,和更新zip文件。而且還可以使用在.NETCompact Framework中。2013-11-11
C#實現(xiàn)Check Password和鎖定輸錯密碼鎖定賬戶功能
C#實現(xiàn)的Check Password,并根據(jù)輸錯密碼的次數(shù)分情況鎖定賬戶:如果輸入錯誤3次,登錄賬戶鎖定5分鐘并提示X點X分后重試登錄,具體實現(xiàn)代碼感興趣的朋友跟隨小編一起看看吧2020-01-01
C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已安裝軟件變化的方法
這篇文章主要介紹了C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已安裝軟件變化的方法,涉及C#針對注冊表的讀取與監(jiān)控技巧,非常具有實用價值,需要的朋友可以參考下2015-08-08
c#創(chuàng)建windows服務(wù)入門教程實例
windows服務(wù)是windows系統(tǒng)中一類特殊的應(yīng)用程序,一般情況下它們只會在后臺運行,不會影響前臺操作,非常適合做一些不需要用戶參與的而又需要長時間執(zhí)行的任務(wù)2014-04-04
C# 9 中新加入的關(guān)鍵詞 init,record,with
這篇文章主要介紹了C# 9 中新加入的關(guān)鍵詞 init,record,with的相關(guān)資料,幫助大家更好的理解和學習c# 9,感興趣的朋友可以了解下2020-08-08
C# PaddleDetection yolo實現(xiàn)印章檢測
這篇文章主要為大家詳細介紹了C#如何結(jié)合PaddleDetection yolo實現(xiàn)印章檢測,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-11-11

