利用C#代碼將html樣式文件與Word文檔互換的方法
一、C#代碼將html樣式文件轉(zhuǎn)為Word文檔
首先有個(gè)這樣的需求,將以下網(wǎng)頁(yè)內(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)通知書(shū)<hr /></td> </tr> <tr> <td style="text-align: left;font-size:20px;">XX</td> </tr> <tr> <td style="text-align: left"> “XXXX物資平臺(tái)”ZY1703220001號(hào)標(biāo)的開(kāi)標(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>資源編號(hào)</th> <th>數(shù)量(噸)</th> <th>中標(biāo)價(jià)格(含稅總金額:元)</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"> 請(qǐng)貴方在收到通知書(shū)的5個(gè)工作日內(nèi)交齊全額貨款并簽訂合同。 </td> </tr> <tr> <td style="text-align: left"> 特此通知。 </td> </tr> <tr> <td style="text-align: right"> XXXX物資平臺(tái) </td> </tr> <tr> <td style="text-align:right"> 2017 年 4月 16 日 </td> </tr> </table> </div> </div>
樣式展示:
第一步:封裝一個(gè)方法
1:在控制器BiddingNoticeManageController創(chuàng)建一個(gè)DownBiddingNoticeModal方法。(采用的MVC模式)
2:根據(jù)id查詢(xún)當(dāng)前中標(biāo)信息(EF)
3:建一個(gè)中標(biāo)通知書(shū)的html模板頁(yè)(數(shù)據(jù)字段自定義占位符)
3-1:注:html模板中不需要<html>、<head>、<title>、<body>等標(biāo)簽。只是單純的div布局標(biāo)簽
3-2:布局標(biāo)簽中的樣式必須是內(nèi)聯(lián),就是寫(xiě)在標(biāo)簽中,不能寫(xiě)在外部.css中。
4:通過(guò)Stream、StreamReader兩個(gè)類(lèi)來(lái)讀取這個(gè)模板文件(返回的是html字符串)。
5:2中查詢(xún)出數(shù)據(jù)(對(duì)應(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:用法:在頁(yè)面前端寫(xiě)一個(gè)a標(biāo)簽指向這個(gè)方法即可下載為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)通知書(shū)<hr /></td> </tr> <tr> <td style="text-align: left;font-size:20px;">@BidderName</td> </tr> <tr> <td style="text-align: left"> “XXXX物資平臺(tái)”@ResourceCode號(hào)標(biāo)的開(kāi)標(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>資源編號(hào)</th> <th>數(shù)量(@Unit)</th> <th>中標(biāo)價(jià)格(含稅總金額:元)</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"> 請(qǐng)貴方在收到通知書(shū)的5個(gè)工作日內(nèi)交齊全額貨款并簽訂合同。 </td> </tr> <tr> <td style="text-align: left"> 特此通知。 </td> </tr> <tr> <td style="text-align: right"> XXXX物資平臺(tái) </td> </tr> <tr> <td style="text-align:right"> @Year 年 @Moth 月 @Day 日 </td> </tr> </table> </div> </div>
/// <summary>
/// 下載中標(biāo)通知書(shū)
/// 用法:前端一個(gè)a標(biāo)簽指向這個(gè)控制器的這個(gè)方法
/// </summary>
/// <param name="id">中標(biāo)通知書(shū)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)通知書(shū).doc");
#endregion
}
/// <summary>
/// 讀取中標(biāo)通知書(shū)模板
/// </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)頁(yè)上,該怎么做呢?這里我提供了一個(gè)小工具,你可以將Word轉(zhuǎn)換為Html,需要顯示的話(huà),可以直接訪問(wèn)該Html,廢話(huà)不多說(shuō),下面看代碼。
頁(yè)面代碼:
<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文檔在客戶(hù)機(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;
// 打開(kāi)文件
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的寫(xiě)法,如果是10,可能寫(xiě)成:
* 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)到新生成的頁(yè)面
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
{
//驗(yàn)證是否為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)前上傳頁(yè)面的同一級(jí)的目錄下面的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文件
這樣就可以簡(jiǎn)單的在Html中展示word文檔中的內(nèi)容,而不需要在自己進(jìn)行編輯了。當(dāng)然,如果有需要的話(huà),可以將轉(zhuǎn)換的Html的路徑存入數(shù)據(jù)庫(kù),根據(jù)不同的條件直接進(jìn)行訪問(wèn)。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)我們的支持。
上一篇:C#圖像亮度調(diào)式與偽彩色圖的處理教程(推薦)
欄 目:C#教程
下一篇:c# textbox的滾動(dòng)條總是指向最底端的簡(jiǎn)單解決方法
本文標(biāo)題:利用C#代碼將html樣式文件與Word文檔互換的方法
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5384.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)將窗體固定在顯示器的左上角且不能移動(dòng)的方法
- 01-10C#實(shí)現(xiàn)將程序鎖定到Win7任務(wù)欄的方法
- 01-10C#利用反射技術(shù)實(shí)現(xiàn)去掉按鈕選中時(shí)的邊框效果
- 01-10C#一個(gè)簡(jiǎn)單的定時(shí)小程序?qū)崿F(xiàn)代碼
- 01-10C#實(shí)現(xiàn)將應(yīng)用程序設(shè)置為開(kāi)機(jī)啟動(dòng)的方法
- 01-10C#獲取網(wǎng)頁(yè)源代碼的方法
- 01-10C#將圖片存放到SQL SERVER數(shù)據(jù)庫(kù)中的方法
- 01-1010個(gè)C#程序員經(jīng)常用到的實(shí)用代碼片段
- 01-10C#導(dǎo)出網(wǎng)站功能實(shí)例代碼講解
- 01-10C#圖片處理3種高級(jí)應(yīng)用


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線(xiàn)程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫(xiě)Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 04-02jquery與jsp,用jquery
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什


