利用C#代码将html样式文件与Word文档互换的方法

时间:2021-10-12 18:50:08

一、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>

样式展示:

利用C#代码将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:关键代码

?
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文件

利用C#代码将html样式文件与Word文档互换的方法

这样就可以简单的在html中展示word文档中的内容,而不需要在自己进行编辑了。当然,如果有需要的话,可以将转换的html的路径存入数据库,根据不同的条件直接进行访问。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。   

原文链接:http://www.cnblogs.com/wendj/p/6699885.html