一、c#代碼將html樣式文件轉為word文檔
首先有個這樣的需求,將以下網頁內容下載為word文件。
html代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
< 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 > |
樣式展示:
第一步:封裝一個方法
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:關鍵代碼
1
2
3
4
5
|
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模板文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
< 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 > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
/// <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,廢話不多說,下面看代碼。
頁面代碼:
1
2
3
4
|
< 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#代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
<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的路徑存入數據庫,根據不同的條件直接進行訪問。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://www.cnblogs.com/wendj/p/6699885.html