js导出execl 兼容ie Chrome Firefox各种主流浏览器(js export execl)

第一种导出table布局的表格

  1 <html>
2
3 <head>
4 <meta charset="utf-8">
5 <script type="text/javascript" language="javascript">
6 var idTmr;
7
8 function getExplorer() {
9 var explorer = window.navigator.userAgent;
10 //ie
11 if(explorer.indexOf(".NET") >= 0) {
12 return 'ie';
13 }
14 //firefox
15 else if(explorer.indexOf("Firefox") >= 0) {
16 return 'Firefox';
17 }
18 //Chrome
19 else if(explorer.indexOf("Chrome") >= 0) {
20 return 'Chrome';
21 }
22 //Opera
23 else if(explorer.indexOf("Opera") >= 0) {
24 return 'Opera';
25 }
26 //Safari
27 else if(explorer.indexOf("Safari") >= 0) {
28 return 'Safari';
29 }
30 }
31
32 function method1(tableid, name, filename) { //整个表格拷贝到EXCEL中
33 if(getExplorer() == 'ie') {
34 var curTbl = document.getElementById(tableid);
35 var oXL = new ActiveXObject("Excel.Application");
36
37 //创建AX对象excel
38 var oWB = oXL.Workbooks.Add();
39 //获取workbook对象
40 var xlsheet = oWB.Worksheets(1);
41 //激活当前sheet
42 var sel = document.body.createTextRange();
43 sel.moveToElementText(curTbl);
44 //把表格中的内容移到TextRange中
45 sel.select();
46 //全选TextRange中内容
47 sel.execCommand("Copy");
48 //复制TextRange中内容
49 xlsheet.Paste();
50 //粘贴到活动的EXCEL中
51 oXL.Visible = true;
52 //设置excel可见属性
53
54 try {
55 var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
56 } catch(e) {
57 print("Nested catch caught " + e);
58 } finally {
59 oWB.SaveAs(fname);
60
61 oWB.Close(savechanges = false);
62 //xls.visible = false;
63 oXL.Quit();
64 oXL = null;
65 //结束excel进程,退出完成
66 //window.setInterval("Cleanup();",1);
67 idTmr = window.setInterval("Cleanup();", 1);
68
69 }
70
71 } else {
72 tableToExcel(tableid, name, filename)
73 }
74 }
75
76 function Cleanup() {
77 window.clearInterval(idTmr);
78 CollectGarbage();
79 }
80 var tableToExcel = (function() {
81 var uri = 'data:application/vnd.ms-excel;base64,',
82 template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
83 base64 = function(s) {
84 return window.btoa(unescape(encodeURIComponent(s)))
85 },
86 format = function(s, c) {
87 return s.replace(/{(\w+)}/g,
88 function(m, p) {
89 return c[p];
90 })
91 }
92 return function(table, name, filename) {
93 if(!table.nodeType) table = document.getElementById(table)
94 var ctx = {
95 worksheet: name || 'Worksheet',
96 table: table.innerHTML
97 }
98 //window.location.href = uri + base64(format(template, ctx))
99 //<a href="/images/logo.png" download="w3clogo"> //参考a链接的下载,更改下载文件名
100 //<img border="0" src="/images/logo.png" alt="w3cschool.cc" >
101 //</a>
102 document.getElementById("dlink").href = uri + base64(format(template, ctx));
103 document.getElementById("dlink").download = filename; //这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
104 document.getElementById("dlink").click();
105 }
106 })()
107 </script>
108 <style>
109 .bk {
110 background-color: red;
111 color: blue;
112 text-align: center;
113 }
114 </style>
115 </head>
116
117 <body>
118 <table id="targetTable">
119 <tr align="center" id='th'>
120 <td>标识</td>
121 <td>内容</td>
122 <td>创建时间</td>
123 </tr>
124 <tr id="tr1" class="bk">
125 <a>
126 <td>1</td>
127 <td>excel01</td>
128 <td>2015-07-22</td>
129 </a>
130 </tr>
131 <tr align="center" style="background-color: red;color:yellow;">
132 <td>2</td>
133 <td>excel02</td>
134 <td>2015-07-22</td>
135 </tr>
136 <tr align="center" id="tr3">
137 <a>
138 <td>1</td>
139 <td>excel01</td>
140 <td>2015-07-22</td>
141 </a>
142 </tr>
143 </table>
144 </br>
145 <span>span</span>
146 <a id="dlink" style="display:none;"></a><!--隐藏链接,设置下载文件名 利用download属性-->
147 <input id="Button1" type="button" value="导出EXCEL" onclick="javascript:method1('targetTable', 'name', 'myfile.xls')" />
148 <script>
149 //导出execl时只有标签上的样式才会影响到导出的execl的样式,通过类渲染的最终样式没用
150 document.getElementById('tr3').style.backgroundColor = "yellow";
151 var th = document.getElementById('th');
152 var a = document.getElementById('tr1');
153 var color = window.getComputedStyle(a).getPropertyValue("background-color"); //获取最终样式,经过class渲染之后的样式
154 //alert(window.getComputedStyle(a).getPropertyValue("color"));
155 th.style.backgroundColor = color;
156 </script>
157 </body>
158
159 </html>

在template的head标签中加了<meta charset="UTF-8">(template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8">......),防止中文乱码。

其中利用了a标签的download属性来更改导出的execl名字,而且导出execl时只有标签上的样式才会影响到导出的execl的样式,通过类渲染的最终样式没用

第二种导出div布局的表格

  1 <!DOCTYPE html>
2
3 <html>
4
5 <head>
6 <meta name="viewport" content="width=device-width" />
7 <meta charset="utf-8">
8 <title>项目统计</title>
9 <link href="css/bootstrap.min.css" rel="stylesheet" />
10 <link href="css/bootstrap-datepicker3.min.css" rel="stylesheet" />
11 <link rel="stylesheet" type="text/css" href="css/layout.css" />
12 <link rel="stylesheet" type="text/css" href="css/style.css" />
13 <script src="js/jquery.min.js"></script>
14 <script src="js/layer.js"></script>
15 <script src="js/bootstrap-datepicker.min.js"></script>
16 <script src="js/bootstrap-datepicker.zh-cn.min.js"></script>
17 <script type="text/javascript" language="javascript">
18 var idTmr;
19
20 function getExplorer() {
21 var explorer = window.navigator.userAgent;
22 //ie
23 if(explorer.indexOf("MSIE") >= 0) {
24 return 'ie';
25 }
26 //firefox
27 else if(explorer.indexOf("Firefox") >= 0) {
28 return 'Firefox';
29 }
30 //Chrome
31 else if(explorer.indexOf("Chrome") >= 0) {
32 return 'Chrome';
33 }
34 //Opera
35 else if(explorer.indexOf("Opera") >= 0) {
36 return 'Opera';
37 }
38 //Safari
39 else if(explorer.indexOf("Safari") >= 0) {
40 return 'Safari';
41 }
42 }
43
44 function method1(tableid,name, filename) { //整个表格拷贝到EXCEL中
45 //隐藏a链接是为了设置下载名字
46 if($('#dlink').length <= 0) //id为dlink的a不存在则创建一个隐藏的a
47 {
48 $('body').prepend("<a id='dlink' style='display:none;'>");
49 }
50 //判断table是不是div布局的table
51 if($("#" + tableid).prop("tagName") == "DIV") {
52 var table = $("#" + tableid).html(); //是div布局的table则重新建一个table,获取html标签替换
53 var tableClass=$("#" + tableid).attr('class'); //获取原来div的class
54 tableid = "divTableID222"; //为了第二次导出execl的时候,不与table的id重复
55 if($('#' + tableid).length <= 0) //id为tableid的div不存在则创建一个隐藏的div
56 {
57 $('body').prepend("</a><div id='" + tableid + "' style='display: none;'></div>");
58 }
59 $('#' + tableid).html(table); //把需要导出的内容加到这个隐藏的div中
60 $("#" + tableid).attr('class',tableClass); //把原来div的样式复制给隐藏div的样式
61 $("#" + tableid+" div[name='exportFilter']").remove(); //删除不要导出的列
62 //下面是替换标签
63 $('#' + tableid + ' .tr-th').replaceWith(function() {
64 return $("<tr />", {
65 html: $(this).html(), class:$(this).attr('class'),
66 //设置execl样式,必须是style属性上的,通过class渲染的不行
67 style:"background-color:"+window.getComputedStyle(this).getPropertyValue("background-color"),
68 align:"center"
69 });
70 });
71 $('#' + tableid + ' .th').replaceWith(function() {
72 return $("<th />", {
73 html: $(this).html(), class:$(this).attr('class'),
74 style:"background-color:"+window.getComputedStyle(this).getPropertyValue("background-color"),
75 align:"center"
76 });
77 });
78 $('#' + tableid + ' .tr').replaceWith(function() {
79 return $("<tr />", {
80 html: $(this).html(), class:$(this).attr('class'),
81 style:"background-color:"+window.getComputedStyle(this).getPropertyValue("background-color"),
82 align:"center"
83 });
84 });
85 $('#' + tableid + ' .td').replaceWith(function() {
86 return $("<td />", {
87 html: $(this).html(), class:$(this).attr('class'),
88 style:"background-color:"+window.getComputedStyle(this).getPropertyValue("background-color")
89 +";color:"+window.getComputedStyle(this).getPropertyValue("color"),
90 align:"center"
91 });
92 });
93 }
94 if(getExplorer() == 'ie') {
95 var curTbl = document.getElementById(tableid);
96 var oXL = new ActiveXObject("Excel.Application");
97
98 //创建AX对象excel
99 var oWB = oXL.Workbooks.Add();
100 //获取workbook对象
101 var xlsheet = oWB.Worksheets(1);
102 //激活当前sheet
103 var sel = document.body.createTextRange();
104 sel.moveToElementText(curTbl);
105 //把表格中的内容移到TextRange中
106 sel.select();
107 //全选TextRange中内容
108 sel.execCommand("Copy");
109 //复制TextRange中内容
110 xlsheet.Paste();
111 //粘贴到活动的EXCEL中
112 oXL.Visible = true;
113 //设置excel可见属性
114
115 try {
116 var fname = oXL.Application.GetSaveAsFilename(filename||'我的execl', "Excel Spreadsheets (*.xls), *.xls");
117 } catch(e) {
118 print("Nested catch caught " + e);
119 } finally {
120 oWB.SaveAs(fname);
121
122 oWB.Close(savechanges = false);
123 //xls.visible = false;
124 oXL.Quit();
125 oXL = null;
126 //结束excel进程,退出完成
127 //window.setInterval("Cleanup();",1);
128 idTmr = window.setInterval("Cleanup();", 1);
129
130 }
131
132 } else {
133 tableToExcel(tableid,name, filename)
134 }
135 }
136
137 function Cleanup() {
138 window.clearInterval(idTmr);
139 CollectGarbage();
140 }
141 var tableToExcel = (function() {
142 var uri = 'data:application/vnd.ms-excel;base64,',
143 template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
144 base64 = function(s) {
145 return window.btoa(unescape(encodeURIComponent(s)))
146 },
147 format = function(s, c) {
148 return s.replace(/{(\w+)}/g,
149 function(m, p) {
150 return c[p];
151 })
152 }
153 return function(table, name, filename) {
154 if(!table.nodeType) table = document.getElementById(table)
155 var ctx = {
156 worksheet: name || 'Worksheet',
157 table: table.innerHTML
158 }
159 //window.location.href = uri + base64(format(template, ctx))
160 //<a href="/images/logo.png" download="w3clogo"> //参考a链接的下载,更改下载文件名,可以添加扩展名w3clogo.jpg
161 //<img border="0" src="/images/logo.png" alt="w3cschool.cc" >
162 //</a>
163 document.getElementById("dlink").href = uri + base64(format(template, ctx));
164 document.getElementById("dlink").download = filename||'我的execl'; //这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
165 //没传参数,下载名字默认为‘我的execl’
166 document.getElementById("dlink").click();
167 }
168 })()
169 </script>
170 </head>
171
172 <body>
173 <div class="info-center">
174 <div class="manage-head">
175 <h6 class="padding-left manage-head-con">
176 项目统计
177
178 <a class="h5 custom-red fr margin-left" href="/ProjectEntering/Index">录入项目</a>
179 <a class="h5 custom-glay fr margin-left" href="/ProjectStatistics/Index?page=1&keyword=&AID=0&Project_state=&Excel=1'">导出Execl</a>
180
181 <select id="SelProject_state" class="h5 custom-glay fr margin-left" style="height: 32px; font-size: 10px; color: #565656; font-weight: normal; border: 1px solid #cecece; padding: 0 10px; margin-top: -5px;">
182 <option value="">状态</option>
183 <option value="">全部</option>
184 <option value="0">进行中</option>
185 <option value="1">完成</option>
186 </select>
187
188 <input id="Button1" type="button" value="导出EXCEL" onclick="javascript:method1('targetTable','name','导出execl')" />
189 <a class="h5 custom-glay fr margin-left" href="javascript:void();" id="akeyword" >搜索</a>
190 <input id="txtkeyword" value="" placeholder="请输入关键字" class="input w20 fr" style="vertical-align: top;" />
191 <div class="span5 col-md-5 fr" id="sandbox-container" >
192 <div class="input-daterange input-group" id="datepicker">
193 <span class="input-group-addon" style="height: 32px; margin-top: -10px; ">时间段</span>
194 <input id="txtstartTime" type="text" class="input-sm form-control" name="start" readonly>
195 <span class="input-group-addon">至</span>
196 <input id="txtendTime" type="text" class="input-sm form-control" name="end" readonly>
197 </div>
198 </div>
199 </h6>
200 </div>
201 <div id="targetTable" class="offcial-table input-table table-margin clearfix">
202 <div class="tr-th clearfix">
203 <div class="th w10">项目编号</div>
204 <div class="th w10">项目名称</div>
205 <div class="th w15">项目金额</div>
206 <div class="th w10">项目负责人</div>
207 <div class="th w10">创建时间</div>
208 <div class="th w10">实际总系数值</div>
209 <div class="th w10">预计总系数值</div>
210 <div class="th w10">项目状态</div>
211 <div class="th w15" name='exportFilter'>操作</div>
212 </div>
213 <div id="projectInfo58" class="tr clearfix tr-check">
214 <a href="/ProjectDetail/Index?PID=58">
215 <div class="td w10">987</div>
216 <div class="td w10">test2017</div>
217 <div class="td w15">¥0</div>
218 <div class="td w10">Katherine </div>
219 <div class="td w10">2017/1/13 15:02:16</div>
220 <div class="td w10">28</div>
221 <div class="td w10" style="color: blue;">20</div>
222 <div class="td w10">
223 <span class="text-blue">
224 进行中
225 </span>
226 </div>
227 <div class="td w15" name='exportFilter'>
228 <a href="/ProjectDetail/Index?PID=58">查看</a>
229 /
230 <a href="/ProjectEntering/Index?PID=58">修改</a>
231 /
232 <a name="aDeleteProject" data-id="58" href="javascript:viod();">删除</a>
233 </div>
234 </a>
235 </div>
236 <div id="projectInfo56" class="tr clearfix tr-check">
237 <a href="/ProjectDetail/Index?PID=56">
238 <div class="td w10">123456789</div>
239 <div class="td w10">test20170113</div>
240 <div class="td w15">¥0</div>
241 <div class="td w10">Katherine </div>
242 <div class="td w10">2017/1/13 14:00:28</div>
243 <div class="td w10">10</div>
244 <div class="td w10">9.5</div>
245 <div class="td w10" >
246 <span class="text-blue">
247 进行中
248 </span>
249 </div>
250 <div class="td w15" name='exportFilter'>
251 <a href="/ProjectDetail/Index?PID=56">查看</a>
252 /
253 <a href="/ProjectEntering/Index?PID=56">修改</a>
254 /
255 <a name="aDeleteProject" data-id="56" href="javascript:viod();">删除</a>
256 </div>
257 </a>
258 </div>
259 <div id="projectInfo53" class="tr clearfix ">
260 <a href="/ProjectDetail/Index?PID=53">
261 <div class="td w10">63</div>
262 <div class="td w10">63</div>
263 <div class="td w15">¥63</div>
264 <div class="td w10">admin</div>
265 <div class="td w10">2017/1/12 17:59:59</div>
266 <div class="td w10">96</div>
267 <div class="td w10">111</div>
268 <div class="td w10">
269 <span class="text-blue">
270 进行中
271 </span>
272 </div>
273 <div class="td w15" name='exportFilter'>
274 <a href="/ProjectDetail/Index?PID=53">查看</a>
275 /
276 <a href="/ProjectEntering/Index?PID=53">修改</a>
277 /
278 <a name="aDeleteProject" data-id="53" href="javascript:viod();">删除</a>
279 </div>
280 </a>
281 </div>
282 <div id="projectInfo52" class="tr clearfix tr-check">
283 <a href="/ProjectDetail/Index?PID=52">
284 <div class="td w10">123-456</div>
285 <div class="td w10">test0112</div>
286 <div class="td w15">¥0</div>
287 <div class="td w10">Katherine </div>
288 <div class="td w10">2017/1/12 13:46:19</div>
289 <div class="td w10">56</div>
290 <div class="td w10">20</div>
291 <div class="td w10">
292 <span class="text-blue">
293 进行中
294 </span>
295 </div>
296 <div class="td w15" name='exportFilter'>
297 <a href="/ProjectDetail/Index?PID=52">查看</a>
298 /
299 <a href="/ProjectEntering/Index?PID=52">修改</a>
300 /
301 <a name="aDeleteProject" data-id="52" href="javascript:viod();">删除</a>
302 </div>
303 </a>
304 </div>
305 <div id="projectInfo50" class="tr clearfix ">
306 <a href="/ProjectDetail/Index?PID=50">
307 <div class="td w10">16-12257-1</div>
308 <div class="td w10">CapitaLand-Chengdu</div>
309 <div class="td w15">¥0</div>
310 <div class="td w10">Frank Xu</div>
311 <div class="td w10">2017/1/12 11:26:14</div>
312 <div class="td w10">0</div>
313 <div class="td w10">100.2</div>
314 <div class="td w10">
315 <span class="text-blue">
316 进行中
317 </span>
318 </div>
319 <div class="td w15" name='exportFilter'>
320 <a href="/ProjectDetail/Index?PID=50">查看</a>
321 /
322 <a href="/ProjectEntering/Index?PID=50">修改</a>
323 /
324 <a name="aDeleteProject" data-id="50" href="javascript:viod();">删除</a>
325 </div>
326 </a>
327 </div>
328 <div id="projectInfo22" class="tr clearfix ">
329 <a href="/ProjectDetail/Index?PID=22">
330 <div class="td w10">test</div>
331 <div class="td w10">test</div>
332 <div class="td w15">¥2</div>
333 <div class="td w10">admin</div>
334 <div class="td w10">2017/1/10 16:12:29</div>
335 <div class="td w10">4.4</div>
336 <div class="td w10">10.5</div>
337 <div class="td w10">
338 <span class="text-green">完成</span>
339 </div>
340 <div class="td w15" name='exportFilter'>
341 <a href="/ProjectDetail/Index?PID=22">查看</a>
342 </div>
343 </a>
344 </div>
345
346 </div>
347 <!-------------分页开始-------------->
348 <div class="show-page padding-big-right ">
349
350 <div class="page">
351 <ul class="offcial-page margin-top margin-big-right">
352 <li>共<em class="margin-small-left margin-small-right">6</em>条数据</li>
353 <li>每页显示<em class="margin-small-left margin-small-right">15</em>条</li>
354 <li>
355 <a class="next disable" href="javascript:void();" id="aPre">上一页</a>
356 </li>
357 <li>
358 <a class="next disable">1</a>
359 </li>
360 <li>
361 <a class="next disable" href="javascript:void();" id="aNext">下一页</a>
362 </li>
363 <li><span class="fl">共<em class="margin-small-left margin-small-right">1</em>页</span></li>
364 </ul>
365 </div>
366 </div>
367 <!-------------分页结束-------------->
368 </div>
369
370
371 </body>
372
373 </html>

这种方式实际是把div处理了一下,重新创建了一个隐藏的div,把div布局的内容转换成table布局的内容放到隐藏的div中,中间用了jq的标签替换。(有更好的方法欢迎讨论)

$('#' + tableid + ' .tr-th').replaceWith(function() {
return $("<tr />", {
html: $(this).html(), class:$(this).attr('class'),
//设置execl样式,必须是style属性上的,通过class渲染的不行
style:"background-color:"+window.getComputedStyle(this).getPropertyValue("background-color"),
align:"center"
});
});

jq替换标签

里面用到基于bootstrap的时间控件 资源下载

上一篇:支持向量机的smo算法(MATLAB code)


下一篇:Android第三方应用分享图文到微信朋友圈 & 微信回调通知分享状态