先上代码
-
<script type="text/javascript" language="javascript">
-
var idTmr;
-
-
function getExplorer() {
-
var explorer = window.navigator.userAgent;
-
//ie
-
if (explorer.indexOf("MSIE") >= 0) {
-
return 'ie';
-
}
-
//firefox
-
else if (explorer.indexOf("Firefox") >= 0) {
-
return 'Firefox';
-
}
-
//Chrome
-
else if (explorer.indexOf("Chrome") >= 0) {
-
return 'Chrome';
-
}
-
//Opera
-
else if (explorer.indexOf("Opera") >= 0) {
-
return 'Opera';
-
}
-
//Safari
-
else if (explorer.indexOf("Safari") >= 0) {
-
return 'Safari';
-
}
-
}
-
-
function method1(tableid,name="1.xlsx") { //整个表格拷贝到EXCEL中
-
if (getExplorer() == 'ie') {
-
var curTbl = document.getElementById(tableid);
-
var oXL = new ActiveXObject("Excel.Application");
-
-
//创建AX对象excel
-
var oWB = oXL.Workbooks.Add();
-
//获取workbook对象
-
var xlsheet = oWB.Worksheets(1);
-
//激活当前sheet
-
var sel = document.body.createTextRange();
-
sel.moveToElementText(curTbl);
-
//把表格中的内容移到TextRange中
-
sel.select;
-
//全选TextRange中内容
-
sel.execCommand("Copy");
-
//复制TextRange中内容
-
xlsheet.Paste();
-
//粘贴到活动的EXCEL中
-
oXL.Visible = true;
-
//设置excel可见属性
-
-
try {
-
var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
-
} catch (e) {
-
print("Nested catch caught " + e);
-
} finally {
-
oWB.SaveAs(fname);
-
-
oWB.Close(savechanges = false);
-
//xls.visible = false;
-
oXL.Quit();
-
oXL = null;
-
//结束excel进程,退出完成
-
//window.setInterval("Cleanup();",1);
-
idTmr = window.setInterval("Cleanup();", 1);
-
-
}
-
-
} else {
-
tableToExcel(tableid,name)
-
}
-
}
-
-
function Cleanup() {
-
window.clearInterval(idTmr);
-
CollectGarbage();
-
}
-
var tableToExcel = (function () {
-
var uri = 'data:application/vnd.ms-excel;base64,',
-
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><!--[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>',
-
base64 = function (s) {
-
return window.btoa(unescape(encodeURIComponent(s)))
-
},
-
format = function (s, c) {
-
return s.replace(/{(\w+)}/g,
-
function (m, p) {
-
return c[p];
-
})
-
}
-
return function (table, name) {
-
console.log(table,name)
-
if (!table.nodeType) table = document.getElementById(table)
-
var ctx = {
-
worksheet: name || 'Worksheet',
-
table: table.innerHTML
-
}
-
return;
-
window.location.href = uri + base64(format(template, ctx))
-
}
-
})();
-
</script>
-
$('#export').click(function () {
-
method1('table');
-
})
$('#export').attr('href',uri + base64(format(template, ctx))) //解决文件无扩展名的问题
转载自http://blog.csdn.net/sinat_15114467/article/details/51098522
github也有写好的插件:
-
jQuery table2excel - v1.1.1
-
* jQuery plugin to export an .xls file in browser from an HTML table
-
* https://github.com/rainabba/jquery-table2excel
这个地址也是相关的介绍https://segmentfault.com/a/1190000000336643
我的html实例
-
<!DOCTYPE html>
-
<html lang="en">
-
<head>
-
<meta charset="gb2312">
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
-
<title>数据</title>
-
<style>
-
* {
-
margin: 0;
-
padding: 0;
-
text-decoration: none;
-
list-style: none;
-
font-size: 20px;
-
}
-
body{
-
text-align: center;
-
}
-
.agent{
-
text-align: left;
-
}
-
table {
-
width: 1200px;
-
margin: 0 auto;
-
vertical-align: center;
-
font-size: 18px;
-
text-align: center;
-
border: 1px solid #ccc;
-
}
-
-
td,
-
th {
-
border: 1px solid #000;
-
overflow: hidden;
-
}
-
-
.kefu {
-
width: 70px;
-
}
-
-
.page {
-
text-align: center;
-
font-size: 20px;
-
}
-
-
.page a {
-
display: inline-block;
-
}
-
-
#export {
-
display: block;
-
text-align: center;
-
font-size: 20px;
-
}
-
/* 时间和日期 */
-
-
#choose {
-
width: 1200px;
-
margin: 20px auto;
-
text-align: center;
-
}
-
/* 对话框 */
-
-
.convBox {
-
position: fixed;
-
top: 0px;
-
left: 0;
-
bottom: 0;
-
right: 0;
-
margin: auto;
-
width: 1200px;
-
height: 500px;
-
overflow: auto;
-
display: none;
-
background: #ccc;
-
border: 1px solid #000;
-
}
-
-
.convBox h6 {
-
font-size: 20px;
-
margin: 15px 0;
-
text-align: center;
-
}
-
-
.convBox .close {
-
position: absolute;
-
top: 8px;
-
right: 8px;
-
font-size: 20px;
-
}
-
-
.convBox li {
-
float: left;
-
margin: 8px 20px;
-
}
-
-
.clearfix:after {
-
content: '';
-
display: block;
-
height: 0;
-
visibility: hidden;
-
clear: both;
-
}
-
-
.clearfix {
-
zoom: 1;
-
}
-
-
.mainCon .agent,
-
.mainCon .client {
-
padding: 8px 20px;
-
}
-
-
.mainCon .client {
-
text-align: right;
-
background: #68c558;
-
}
-
</style>
-
</head>
-
<body>
-
<div id="choose">
-
<input type="text" class="startTm">
-
<input type="text" class="endTm">
-
<button>提交</button>
-
</div>
-
<table id="table">
-
<tr>
-
<th>编号</th>
-
<th>对话开始时间</th>
-
<th>会话结束时间</th>
-
<th>客户id</th>
-
<th>搜索关键词</th>
-
<th class="kefu">客服</th>
-
<th>客服首次响应访客的等待时</th>
-
<th>访客的消息数</th>
-
<th>对话内容</th>
-
<th>客户地点</th>
-
<th>IP</th>
-
</tr>
-
</table>
-
<p class="page">
-
<a href="javascript:void(0)" class="prev">上一页</a>
-
<a href="javascript:void(0)" class="next">下一页</a>
-
<span></span>
-
</p>
-
<a href="javascript:void(0)" id="export" download="对话记录.xlsx">导出对话记录</a>
-
<div class="convBox">
-
<h6><span></span>的对话</h6>
-
<a href="javascript:void(0)" class="close">X</a>
-
<ul class="contentKey clearfix">
-
<li class="agent_name">
-
客服:<span>dfsdfsfs</span>
-
</li>
-
<li class="wait_in_secs">
-
对话等待时间:<span>5</span>S
-
</li>
-
<li class="visitor_ip">
-
IP:<span>yan</span>
-
</li>
-
<li class="visitor_location">
-
地点:<span>yan</span>
-
</li>
-
<li class="search_engine_kw">
-
搜索关键词:<span>sdfsfsfsdfsfsfsgsdsg</span>
-
</li>
-
<li class="conv_start_tm">
-
对话开始时间:<span>sdfsfsfsdfsfsfsgsdsg</span>
-
</li>
-
<li class="conv_end_tm">
-
对话结束时间:<span>sdfsfsfsdfsfsfsgsdsg</span>
-
</li>
-
</ul>
-
<div class="mainCon clearfix">
-
-
</div>
-
</div>
-
<script src="js/jquery-1.11.3.min.js"></script>
-
<script>
-
var tableList= '<tr>\
-
<th>编号</th>\
-
<th>对话开始时间</th>\
-
<th>会话结束时间</th>\
-
<th>客户id</th>\
-
<th>搜索关键词</th>\
-
<th class="kefu">客服</th>\
-
<th>客服首次响应访客的等待时</th>\
-
<th>访客的消息数</th>\
-
<th>对话内容</th>\
-
<th>客户地点</th>\
-
<th>IP</th>\
-
</tr>';
-
$(document).ready(function () {
-
var pageAll='';//计算总数时用的参数
-
var pagesize = 0; //显示页
-
var limit = 20; //每页显示的数目
-
var offset = pagesize * limit; //跳过的数目
-
var startTm = $('.startTm').val();
-
var endTm = $('.endTm').val();
-
//初始化时间
-
var startTm = getFormatDate('ymd');
-
var endTm = getFormatDate('ymd');
-
$('.startTm').val(getFormatDate('ymd'));
-
$('.endTm').val(getFormatDate('ymd'));
-
-
var data1 = {
-
startTm: startTm,
-
endTm: endTm,
-
offset: 0
-
};
-
//ajax请求
-
function ajax(data1) {
-
// console.log(data1)
-
$.ajax({
-
url: "php/index.php",
-
data: data1,
-
success: function (data) {
-
console.log(data)
-
var newJson = JSON.parse(data);
-
if (newJson.result.length < 20) {
-
$('.page span').text("已经是最后一页");
-
} else if (newJson.result.length <= 0) {
-
$('.page span').text("已经是最后一页");
-
return;
-
} else {
-
var Nowpage = pagesize + 1;
-
$('.page span').text("当前是第" + Nowpage + "页");
-
}
-
// addContent(newJson.result)
-
tableList+=addContent(newJson.result);
-
$('#table').append(addContent(newJson.result));
-
}
-
})
-
}
-
function ajax2(data1) {
-
$.ajax({
-
url: "php/index.php",
-
data: data1,
-
success: function (data) {
-
var newJson = JSON.parse(data);
-
tableList+=addContent(newJson.result);
-
if (newJson.result.length < 20 || newJson.result.length <= 0) {
-
// console.log(tableList)
-
var dateN=(new Date()).toLocaleString();
-
// console.log(dateN)
-
// return;
-
method1(tableList,dateN);
-
// return tableList;
-
} else {
-
allrecord();
-
}
-
}
-
})
-
}
-
//调出所有的记录
-
function allrecord(){
-
pageAll++;
-
var offset = pageAll * limit; //跳过的数目
-
var startTm = $('.startTm').val();
-
var endTm = $('.endTm').val();
-
var data1 = {
-
startTm: startTm,
-
endTm: endTm,
-
offset: offset
-
}
-
ajax2(data1);
-
}
-
ajax(data1);
-
//插入对话内容
-
function addContent(rs) {
-
// console.log(rs)
-
var arr = [];
-
var length = rs.length;
-
for (var i = 0; i < length; i++) {
-
if(!rs[i]){continue;}
-
arr.push('<tr>');
-
arr.push('<td>' + i + '</td>');
-
arr.push('<td>' + rs[i].conv_start_tm + '</td>');
-
arr.push('<td>' + rs[i].conv_end_tm + '</td>');
-
arr.push('<td>' + rs[i].client_info.visitor_name + '</td>');
-
arr.push('<td>' + rs[i].search_engine_kw + '</td>');
-
arr.push('<td>' + rs[i].agent_name + '</td>');
-
arr.push('<td>' + rs[i].wait_in_secs + '</td>');
-
arr.push('<td>' + rs[i].conv_visitor_msg_count + '</td>');
-
if(rs[i].conv_visitor_msg_count>0){
-
let con = '';
-
let conLen = rs[i].conv_content.length;
-
for(let j=0;j<conLen;j++){
-
con+=rs[i].conv_content[j].from+rs[i].conv_content[j].timestamp+rs[i].conv_content[j].content;
-
}
-
arr.push('<td class="convId">' + con + '<span>' + rs[i].conv_id + '</span></td>');
-
}else{
-
arr.push('<td class="convId">' + '点击显示内容<span>' + rs[i].conv_id + '</span></td>');
-
}
-
arr.push('<td>' + rs[i].visitor_location + '</td>');
-
arr.push('<td>'+rs[i].visitor_ip+'</td>');
-
arr.push('</tr>');
-
}
-
// tableList+=arr.join('')
-
// $('#table').append(arr.join(''));
-
return arr.join('');
-
}
-
$('.prev').click(function () {
-
$("#table tr").not($("#table tr:first")).remove();
-
pagesize = (--pagesize < 0) ? 0 : pagesize;
-
offset = pagesize * limit; //跳过的数目
-
startTm = $('.startTm').val();
-
endTm = $('.endTm').val();
-
var data1 = {
-
startTm: startTm,
-
endTm: endTm,
-
offset: offset
-
}
-
ajax(data1);
-
})
-
$('.next').click(function () {
-
$("#table tr").not($("#table tr:first")).remove();
-
if ($('.page span').text() == '已经是最后一页') {
-
return false;
-
}
-
pagesize = (++pagesize < 0) ? 0 : pagesize;
-
// console.log(pagesize)
-
var offset = pagesize * limit; //跳过的数目
-
var startTm = $('.startTm').val();
-
var endTm = $('.endTm').val();
-
var data1 = {
-
startTm: startTm,
-
endTm: endTm,
-
offset: offset
-
}
-
ajax(data1);
-
})
-
// 日期选择表单
-
$('#choose button').click(function () {
-
pagesize=0;
-
var startTm = $('.startTm').val();
-
var endTm = $('.endTm').val();
-
var data1 = {
-
startTm: startTm,
-
endTm: endTm,
-
offset: 0
-
}
-
$("#table tr").not($("#table tr:first")).remove();
-
ajax(data1);
-
});
-
// 当前时间的函数
-
/*
-
* @param param string 确定时间的显示格式 'ymd' => 年-月-日
-
* 其它 => 年-月-日+时:分:秒
-
* @param num num +1代表后一天,-1代表前一天
-
*
-
**/
-
function getFormatDate(param, num = 0) {
-
var date = new Date();
-
var seperator1 = "-";
-
var seperator2 = ":";
-
var seperator3 = '+';
-
var y = date.getFullYear();
-
var m = date.getMonth() + 1;
-
var d = date.getDate() + num;
-
var h = date.getHours();
-
var i = date.getMinutes();
-
var s = date.getSeconds();
-
if (m >= 1 && m <= 9) {
-
m = "0" + m;
-
}
-
d = d <= 0 ? 1 : d;
-
if (d >= 0 && d <= 9) {
-
d = "0" + d;
-
}
-
if (param = 'ymd') {
-
var currentdate = y + seperator1 + m + seperator1 + d;
-
} else {
-
var currentdate = y + seperator1 + m + seperator1 + d +
-
seperator3 + h + seperator2 + i +
-
seperator2 + s;
-
}
-
return currentdate;
-
}
-
// 显示聊天内容
-
$(document).on('click', '.convId', function () {
-
var convId = $(this).find('span').text();
-
var data1 = {
-
conv_id: convId
-
}
-
$.ajax({
-
url: "php/conv.php",
-
data: data1,
-
success: function (data) {
-
var newJson = (new Function("", "return " + data))(data).result;
-
// console.log(newJson)
-
$('.convBox h6 span').text(convId);
-
$('.convBox .agent_name span').text(newJson.agent_name);
-
$('.convBox .wait_in_secs span').text(newJson.wait_in_secs);
-
$('.convBox .visitor_ip span').text(newJson.visitor_ip);
-
$('.convBox .visitor_location span').text(newJson.visitor_location);
-
$('.convBox .search_engine_kw span').text(newJson.search_engine_kw);
-
$('.convBox .conv_end_tm span').text(newJson.conv_end_tm);
-
$('.convBox .conv_start_tm span').text(newJson.conv_start_tm);
-
$('.convBox .visitor_location span').text(newJson.visitor_location);
-
let convLen = newJson.conv_content.length;
-
let conv_content = [];
-
// console.log(convLen)
-
for (let j = 0; j < convLen; j++) {
-
// conv_content.push(111)
-
conv_content.push('<div class="' + newJson.conv_content[j].from +
-
'"><p>' + newJson.conv_content[j].timestamp + '</p>' +
-
newJson.conv_content[j].content + '</div>');
-
}
-
// console.log(conv_content)
-
$('.convBox .mainCon').html(conv_content.join(''));
-
}
-
});
-
$('.convBox').show();
-
})
-
$(document).on('click', '.convBox .close', function () {
-
$('.convBox').hide();
-
});
-
// 打印
-
$('#export').click(function () {
-
if ($('.page span').text() == '已经是最后一页') {
-
// method1(tableList,'聊天数据');
-
method1(tableList,'1.xlsx');
-
return false;
-
}
-
-
pageAll =pagesize;
-
allrecord();
-
// method1(allrecord(),'美洽对话');
-
})
-
});
-
</script>
-
<script type="text/javascript" language="javascript">
-
var idTmr;
-
-
function getExplorer() {
-
var explorer = window.navigator.userAgent;
-
//ie
-
if (explorer.indexOf("MSIE") >= 0) {
-
return 'ie';
-
}
-
//firefox
-
else if (explorer.indexOf("Firefox") >= 0) {
-
return 'Firefox';
-
}
-
//Chrome
-
else if (explorer.indexOf("Chrome") >= 0) {
-
return 'Chrome';
-
}
-
//Opera
-
else if (explorer.indexOf("Opera") >= 0) {
-
return 'Opera';
-
}
-
//Safari
-
else if (explorer.indexOf("Safari") >= 0) {
-
return 'Safari';
-
}
-
}
-
-
function method1(tableid,name="1.xlsx") { //整个表格拷贝到EXCEL中
-
if (getExplorer() == 'ie') {
-
var curTbl = document.getElementById(tableid);
-
var oXL = new ActiveXObject("Excel.Application");
-
-
//创建AX对象excel
-
var oWB = oXL.Workbooks.Add();
-
//获取workbook对象
-
var xlsheet = oWB.Worksheets(1);
-
//激活当前sheet
-
var sel = document.body.createTextRange();
-
sel.moveToElementText(curTbl);
-
//把表格中的内容移到TextRange中
-
sel.select;
-
//全选TextRange中内容
-
sel.execCommand("Copy");
-
//复制TextRange中内容
-
xlsheet.Paste();
-
//粘贴到活动的EXCEL中
-
oXL.Visible = true;
-
//设置excel可见属性
-
-
try {
-
var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
-
} catch (e) {
-
print("Nested catch caught " + e);
-
} finally {
-
oWB.SaveAs(fname);
-
oWB.Close(savechanges = false);
-
//xls.visible = false;
-
oXL.Quit();
-
oXL = null;
-
//结束excel进程,退出完成
-
//window.setInterval("Cleanup();",1);
-
idTmr = window.setInterval("Cleanup();", 1);
-
-
}
-
-
} else {
-
tableToExcel(tableid,name)
-
}
-
}
-
-
function Cleanup() {
-
window.clearInterval(idTmr);
-
CollectGarbage();
-
}
-
var tableToExcel = (function() {
-
var uri = 'data:application/vnd.ms-excel;base64,', 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><!--[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>'
-
, base64 = function(s) {
-
return window.btoa(unescape(encodeURIComponent(s)))
-
}
-
, format = function(s, c) {
-
return s.replace(/{(\w+)}/g, function(m, p) {
-
return c[p];
-
})
-
}
-
return function(table, name) {
-
var ctx = {worksheet:name , table:table}
-
// console.log(uri + base64(format(template, ctx)))
-
// return;
-
// $('#export').attr('href',uri + base64(format(template, ctx)))
-
window.location.href = uri + base64(format(template, ctx));
-
}
-
})()
-
</script>
-
</body>
-
-
</html>
https://blog.csdn.net/qiphon3650/article/details/77921087
现在各大浏览器基本都支持data协议,所以我们可以使用该协议去将网页中的table转化为excel下载下来
- 对html 进行base64编码处理
- 编码后的html内容增加前缀 data:application/vnd.ms-excel; ,即可使浏览器将其中的数据当做excel来处理,浏览器将提示下载或打开excel文件
代码小例:
<html>
<head>
<meta http-equiv="content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
function base64 (content) {
return window.btoa(unescape(encodeURIComponent(content)));
}
function exportOffice(tableID){
var type = 'doc';
var table = document.getElementById(tableID);
var excelContent = table.innerHTML;
var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
excelFile += "<head>";
excelFile += "<!--[if gte mso 9]>";
excelFile += "<xml>";
excelFile += "<x:ExcelWorkbook>";
excelFile += "<x:ExcelWorksheets>";
excelFile += "<x:ExcelWorksheet>";
excelFile += "<x:Name>";
excelFile += "{worksheet}";
excelFile += "</x:Name>";
excelFile += "<x:WorksheetOptions>";
excelFile += "<x:DisplayGridlines/>";
excelFile += "</x:WorksheetOptions>";
excelFile += "</x:ExcelWorksheet>";
excelFile += "</x:ExcelWorksheets>";
excelFile += "</x:ExcelWorkbook>";
excelFile += "</xml>";
excelFile += "<![endif]-->";
excelFile += "</head>";
excelFile += "<body>";
excelFile += excelContent;
excelFile += "</body>";
excelFile += "</html>";
var base64data = "base64," + base64(excelFile);
switch(type){
case 'excel':
window.open('data:application/vnd.ms-'+type+';'+base64data);
break;
case 'powerpoint':
window.open('data:application/vnd.ms-'+type+';'+base64data);
break;
}
}
</script>
</head>
<body>
<table id="targetTable">
<tr align="center">
<th>名次</th>
<th>姓名</th>
<th>成绩</th>
</tr>
<tr align="center">
<td>1</td>
<td>小明</td>
<td>100</td>
</tr>
<tr align="center">
<td>2</td>
<td>小红</td>
<td>95.5</td>
</tr>
</table>
</br>
<input id="Button1" type="button" value="导出"
onclick="exportOffice('targetTable')" />
</body>
</html>
链接:https://www.jianshu.com/p/a3642877d590
这五种方法前四种方法只支持IE浏览器,最后一个方法支持当前主流的浏览器(火狐,IE,Chrome,Opera,Safari)
-
<!DOCTYPE html>
-
<html>
-
<head lang="en">
-
<meta charset="UTF-8">
-
<title>html 表格导出道</title>
-
<script language="JavaScript" type="text/javascript">
-
//第一种方法
-
function method1(tableid) {
-
-
var curTbl = document.getElementById(tableid);
-
var oXL = new ActiveXObject("Excel.Application");
-
var oWB = oXL.Workbooks.Add();
-
var oSheet = oWB.ActiveSheet;
-
var sel = document.body.createTextRange();
-
sel.moveToElementText(curTbl);
-
sel.select();
-
sel.execCommand("Copy");
-
oSheet.Paste();
-
oXL.Visible = true;
-
-
}
-
//第二种方法
-
function method2(tableid)
-
{
-
-
var curTbl = document.getElementById(tableid);
-
var oXL = new ActiveXObject("Excel.Application");
-
var oWB = oXL.Workbooks.Add();
-
var oSheet = oWB.ActiveSheet;
-
var Lenr = curTbl.rows.length;
-
for (i = 0; i < Lenr; i++)
-
{ var Lenc = curTbl.rows(i).cells.length;
-
for (j = 0; j < Lenc; j++)
-
{
-
oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText;
-
-
}
-
-
}
-
oXL.Visible = true;
-
}
-
//第三种方法
-
function getXlsFromTbl(inTblId, inWindow){
-
-
try {
-
var allStr = "";
-
var curStr = "";
-
if (inTblId != null && inTblId != "" && inTblId != "null") {
-
-
curStr = getTblData(inTblId, inWindow);
-
-
}
-
if (curStr != null) {
-
allStr += curStr;
-
}
-
-
else {
-
-
alert("你要导出的表不存在");
-
return;
-
}
-
var fileName = getExcelFileName();
-
doFileExport(fileName, allStr);
-
-
}
-
-
catch(e) {
-
-
alert("导出发生异常:" + e.name + "->" + e.description + "!");
-
-
}
-
-
}
-
-
function getTblData(inTbl, inWindow) {
-
-
var rows = 0;
-
var tblDocument = document;
-
if (!!inWindow && inWindow != "") {
-
-
if (!document.all(inWindow)) {
-
return null;
-
}
-
-
else {
-
tblDocument = eval(inWindow).document;
-
}
-
-
}
-
-
var curTbl = tblDocument.getElementById(inTbl);
-
var outStr = "";
-
if (curTbl != null) {
-
for (var j = 0; j < curTbl.rows.length; j++) {
-
for (var i = 0; i < curTbl.rows[j].cells.length; i++) {
-
-
if (i == 0 && rows > 0) {
-
outStr += " t";
-
rows -= 1;
-
}
-
-
outStr += curTbl.rows[j].cells[i].innerText + "t";
-
if (curTbl.rows[j].cells[i].colSpan > 1) {
-
for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {
-
outStr += " t";
-
}
-
}
-
if (i == 0) {
-
if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {
-
rows = curTbl.rows[j].cells[i].rowSpan - 1;
-
}
-
}
-
}
-
outStr += "rn";
-
}
-
}
-
-
else {
-
outStr = null;
-
alert(inTbl + "不存在 !");
-
}
-
return outStr;
-
}
-
-
function getExcelFileName() {
-
var d = new Date();
-
var curYear = d.getYear();
-
var curMonth = "" + (d.getMonth() + 1);
-
var curDate = "" + d.getDate();
-
var curHour = "" + d.getHours();
-
var curMinute = "" + d.getMinutes();
-
var curSecond = "" + d.getSeconds();
-
if (curMonth.length == 1) {
-
curMonth = "0" + curMonth;
-
}
-
-
if (curDate.length == 1) {
-
curDate = "0" + curDate;
-
}
-
-
if (curHour.length == 1) {
-
curHour = "0" + curHour;
-
}
-
-
if (curMinute.length == 1) {
-
curMinute = "0" + curMinute;
-
}
-
-
if (curSecond.length == 1) {
-
curSecond = "0" + curSecond;
-
}
-
var fileName = "table" + "_" + curYear + curMonth + curDate + "_"
-
+ curHour + curMinute + curSecond + ".csv";
-
return fileName;
-
-
}
-
-
function doFileExport(inName, inStr) {
-
var xlsWin = null;
-
if (!!document.all("glbHideFrm")) {
-
xlsWin = glbHideFrm;
-
}
-
else {
-
var width = 6;
-
var height = 4;
-
var openPara = "left=" + (window.screen.width / 2 - width / 2)
-
+ ",top=" + (window.screen.height / 2 - height / 2)
-
+ ",scrollbars=no,width=" + width + ",height=" + height;
-
xlsWin = window.open("", "_blank", openPara);
-
}
-
xlsWin.document.write(inStr);
-
xlsWin.document.close();
-
xlsWin.document.execCommand('Saveas', true, inName);
-
xlsWin.close();
-
-
}
-
-
//第四种
-
function method4(tableid){
-
-
var curTbl = document.getElementById(tableid);
-
var oXL;
-
try{
-
oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel
-
}catch(e){
-
alert("无法启动Excel!\n\n如果您确信您的电脑中已经安装了Excel,"+"那么请调整IE的安全级别。\n\n具体操作:\n\n"+"工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用");
-
return false;
-
}
-
var oWB = oXL.Workbooks.Add(); //获取workbook对象
-
var oSheet = oWB.ActiveSheet;//激活当前sheet
-
var sel = document.body.createTextRange();
-
sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中
-
sel.select(); //全选TextRange中内容
-
sel.execCommand("Copy");//复制TextRange中内容
-
oSheet.Paste();//粘贴到活动的EXCEL中
-
oXL.Visible = true; //设置excel可见属性
-
var fname = oXL.Application.GetSaveAsFilename("将table导出到excel.xls", "Excel Spreadsheets (*.xls), *.xls");
-
oWB.SaveAs(fname);
-
oWB.Close();
-
oXL.Quit();
-
}
-
-
-
//第五种方法
-
var idTmr;
-
function getExplorer() {
-
var explorer = window.navigator.userAgent ;
-
//ie
-
if (explorer.indexOf("MSIE") >= 0) {
-
return 'ie';
-
}
-
//firefox
-
else if (explorer.indexOf("Firefox") >= 0) {
-
return 'Firefox';
-
}
-
//Chrome
-
else if(explorer.indexOf("Chrome") >= 0){
-
return 'Chrome';
-
}
-
//Opera
-
else if(explorer.indexOf("Opera") >= 0){
-
return 'Opera';
-
}
-
//Safari
-
else if(explorer.indexOf("Safari") >= 0){
-
return 'Safari';
-
}
-
}
-
function method5(tableid) {
-
if(getExplorer()=='ie')
-
{
-
var curTbl = document.getElementById(tableid);
-
var oXL = new ActiveXObject("Excel.Application");
-
var oWB = oXL.Workbooks.Add();
-
var xlsheet = oWB.Worksheets(1);
-
var sel = document.body.createTextRange();
-
sel.moveToElementText(curTbl);
-
sel.select();
-
sel.execCommand("Copy");
-
xlsheet.Paste();
-
oXL.Visible = true;
-
-
try {
-
var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
-
} catch (e) {
-
print("Nested catch caught " + e);
-
} finally {
-
oWB.SaveAs(fname);
-
oWB.Close(savechanges = false);
-
oXL.Quit();
-
oXL = null;
-
idTmr = window.setInterval("Cleanup();", 1);
-
}
-
-
}
-
else
-
{
-
tableToExcel(tableid)
-
}
-
}
-
function Cleanup() {
-
window.clearInterval(idTmr);
-
CollectGarbage();
-
}
-
var tableToExcel = (function() {
-
var uri = 'data:application/vnd.ms-excel;base64,',
-
template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
-
base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) },
-
format = function(s, c) {
-
return s.replace(/{(\w+)}/g,
-
function(m, p) { return c[p]; }) }
-
return function(table, name) {
-
if (!table.nodeType) table = document.getElementById(table)
-
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
-
window.location.href = uri + base64(format(template, ctx))
-
}
-
})()
-
-
</script>
-
</head>
-
<body>
-
-
<div >
-
<button type="button" onclick="method1('tableExcel')">导出Excel方法一</button>
-
<button type="button" onclick="method2('tableExcel')">导出Excel方法二</button>
-
<button type="button" onclick="getXlsFromTbl('tableExcel','myDiv')">导出Excel方法三</button>
-
<button type="button" onclick="method4('tableExcel')">导出Excel方法四</button>
-
<button type="button" onclick="method5('tableExcel')">导出Excel方法五</button>
-
</div>
-
<div id="myDiv">
-
<table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
-
<tr>
-
<td colspan="5" align="center">html 表格导出道Excel</td>
-
</tr>
-
<tr>
-
<td>列标题1</td>
-
<td>列标题2</td>
-
<td>类标题3</td>
-
<td>列标题4</td>
-
<td>列标题5</td>
-
</tr>
-
<tr>
-
<td>aaa</td>
-
<td>bbb</td>
-
<td>ccc</td>
-
<td>ddd</td>
-
<td>eee</td>
-
</tr>
-
<tr>
-
<td>AAA</td>
-
<td>BBB</td>
-
<td>CCC</td>
-
<td>DDD</td>
-
<td>EEE</td>
-
</tr>
-
<tr>
-
<td>FFF</td>
-
<td>GGG</td>
-
<td>HHH</td>
-
<td>III</td>
-
<td>JJJ</td>
-
</tr>
-
</table>
-
</div>
-
</body>
-
</html>
今天上来发现,好多人,会遇到文件名,格式等问题。这里添加一种方法。兼容性我没有测试,大家可以试下,不过需要利用JQ直接贴代码了。jquery 引入文件在http://download.csdn.net/download/aa122273328/10103711 注意一定要引jquery-3.2.1.min.js,jquery.table2excel.js对应的文件。jquery-3.2.1.min.js这个看你对应的文件版本,不重要。如有问题,欢迎批评指导。
-
<!DOCTYPE html>
-
<html>
-
<head lang="en">
-
<meta charset="UTF-8">
-
<title>html 表格导出道</title>
-
<script src="js/vendor/jquery-3.2.1.min.js"></script>
-
<script src="jquery.table2excel.js"></script>
-
<script language="JavaScript" type="text/javascript">
-
-
$(document).ready(function () {
-
$("#btnExport").click(function () {
-
$("#tableExcel").table2excel({
-
exclude : ".noExl", //过滤位置的 css 类名
-
filename : "你想说啥" + new Date().getTime() + ".xls", //文件名称
-
name: "Excel Document Name.xlsx",
-
exclude_img: true,
-
exclude_links: true,
-
exclude_inputs: true
-
-
});
-
});
-
});
-
-
</script>
-
</head>
-
<body>
-
-
<div >
-
-
<button type="button" id="btnExport" onclick="method5('tableExcel')">导出Excel</button>
-
</div>
-
<div id="myDiv">
-
<table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
-
<tr>
-
<td colspan="5" align="center">html 表格导出道Excel</td>
-
</tr>
-
<tr>
-
<td>列标题1</td>
-
<td>列标题2</td>
-
<td>类标题3</td>
-
<td>列标题4</td>
-
<td>列标题5</td>
-
</tr>
-
<tr>
-
<td>aaa</td>
-
<td>bbb</td>
-
<td>ccc</td>
-
<td>ddd</td>
-
<td>eee</td>
-
</tr>
-
<tr>
-
<td>AAA</td>
-
<td>BBB</td>
-
<td>CCC</td>
-
<td>DDD</td>
-
<td>EEE</td>
-
</tr>
-
<tr>
-
<td>FFF</td>
-
<td>GGG</td>
-
<td>HHH</td>
-
<td>III</td>
-
<td>JJJ</td>
-
</tr>
-
</table>
-
</div>
-
</body>
-
</html>
https://blog.csdn.net/aa122273328/article/details/50388673
有时候我们需要把网页中的数据导出excel格式来,那么我们用下面两种方法可以完成。
第一种.自写代码
<html>
<head>
<meta http-equiv="content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
function base64 (content) {
return window.btoa(unescape(encodeURIComponent(content)));
}
/*
*@tableId: table的Id
*@fileName: 要生成excel文件的名字(不包括后缀,可随意填写)
*/
function tableToExcel(tableID,fileName){
var table = document.getElementById(tableID);
var excelContent = table.innerHTML;
var excelFile = "<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'>";
excelFile += "<head><!--[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>";
excelFile += "<body><table>";
excelFile += excelContent;
excelFile += "</table></body>";
excelFile += "</html>";
var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
var a = document.createElement("a");
a.download = fileName+".xlsx";
a.href = link;
a.click();
}
</script>
</head>
<body>
<button type="button" onclick="tableToExcel('item','data')">导出</button>
<table id="item">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr>
<td>1</td>
<td>小明</td>
<td>19</td>
</tr>
<tr>
<td>2</td>
<td>小芳</td>
<td>20</td>
</tr>
<tr>
<td>3</td>
<td>大军</td>
<td>22</td>
</tr>
</table>
</body>
</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
**
第二种.jquery插件
**
首先要先下载一个jquery.table2excel.js插件(网上搜搜),然后使用。
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>table2excel</title>
<link rel="stylesheet" href="http://libs.baidu.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<header class="jq22-header">
<h4>table2excel-可将HTML表格内容导出到Excel中的jQuery插件 <span>jQuery Plugin to export HTML tabled to Excel Spreadsheet Compatible Files</span></h4>
</header>
<section class="jq22-container">
<div class="container" style="padding:30px 0">
<div class="row">
<div class="md-col-8">
<div class="table-responsive table2excel" data-tableName="Test Table 1">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr class="noExl">
<td class="danger">带<code>noExl</code>class的行不会被输出到excel中</td>
<td class="danger">带<code>noExl</code>class的行不会被输出到excel中</td>
</tr>
<tr>
<td class="success">这一行会被导出到excel中</td>
<td class="success">这一行会被导出到excel中</td>
</tr>
</thead>
<tbody>
<tr>
<td>单元格1-1</td>
<td>单元格1-2</td>
</tr>
<tr>
<td>单元格2-1</td>
<td>单元格2-2</td>
</tr>
<tr>
<td>单元格3-1</td>
<td>单元格3-2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" class="warning">合并2个单元格</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<button id="btn" class="btn btn-primary">点击这里将表格内容导出到excel中</button>
</div>
</section>
<script src="http://www.jq22.com/jquery/1.11.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js"><\/script>')</script>
<script src="dist/jquery.table2excel.js"></script>
<script>
$(function() {
$("#btn").click(function(){
$(".table2excel").table2excel({
exclude: ".noExl",
name: "Excel Document Name",
filename: "myFileName",
exclude_img: true,
exclude_links: true,
exclude_inputs: true
});
});
});
</script>
</body>
</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
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
详情请浏览:html中table导出Excel
jquery-table2excel是一款可以将HTML表格的内容导出到微软Excel电子表格中的jQuery插件。该插件可以根据你的需要导出表格中的内容,不需要的行可以不导出。它文件体积小,使用非常方便。
jquery-table2excel插件的github地址为:https://github.com/rainabba/jquery-table2excel
注意导出的Excel文件的格式,默认导出为.xlsx
格式的excel文件,需要excel2010以上的版本才能打开,如果是使用低版本的excel,可以手动将文件扩展名修改为.xls
。
使用方法
使用table2excel表格插件需要在页面中引入jquery和jquery.table2excel.js文件。
-
<script type="text/javascript" src="js/jquery.min.js"></script>
-
<script type="text/javascript" src="js/jquery.table2excel.js"></script>
如果表格中的某一行不需要导出到Excel中,可以为这一行添加.noExl
class类,该class类会在插件初始化时通过参数被指定为不被导出的数据。
初始化插件
在页面DOM元素加载中完毕之后,可以通过下面的方法来初始化table2excel插件。
-
$("#table2excel").table2excel({
-
// 不被导出的表格行的CSS class类
-
exclude: ".noExl",
-
// 导出的Excel文档的名称
-
name: "Excel Document Name",
-
// Excel文件的名称
-
filename: "myExcelTable"
-
});
配置参数
table2excel插件的可用配置参数有:
-
exclude
:不被导出的表格行的CSS class类。 -
name
:导出的Excel文档的名称。 -
filename
:Excel文件的名称。 -
exclude_img
:是否导出图片。 -
exclude_links
:是否导出超链接 -
exclude_inputs
:是否导出输入框中的内容。
-
<!DOCTYPE html>
-
<html lang="en">
-
<head>
-
<meta charset="UTF-8">
-
-
</head>
-
<body>
-
<table border="0" cellspacing="0" cellpadding="0" id="datatable" class="xd_table_sj">
-
-
<tbody>
-
<tr>
-
<td><div align="center" id="titlelable">起始时间</div></td>
-
<td><div align="center" id="titlelable">通信地点</div></td>
-
<td><div align="center" id="titlelable">上网方式</div></td>
-
<td><div align="center" id="titlelable">总时长</div></td>
-
<td><div align="center" id="titlelable">总流量</div></td>
-
<td><div align="center" id="titlelable">套餐优惠</div></td>
-
<td><div align="center" id="titlelable">优惠或减免</div></td>
-
<td><div align="center" id="titlelable">通信费</div></td>
-
<td><div align="center" id="titlelable">终端类型</div></td>
-
</tr>
-
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 01:57:05</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.001</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 01:58:55</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.007</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 07:00:00</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.001</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 07:23:19</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.084</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 08:16:31</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.001</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 08:16:39</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.06</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 08:28:44</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.002</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 08:34:50</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.259</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 08:34:50</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>1.26</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 09:54:53</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>1.357</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 09:56:29</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.003</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 09:56:31</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.009</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 09:56:33</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.583</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 10:27:16</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.001</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 10:28:58</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.004</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 12:44:12</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.001</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 12:45:41</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.411</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 12:57:42</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.024</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
-
<td>10-01 12:57:50</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.009</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
<tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
-
<td>10-01 12:57:52</td>
-
<td></td>
-
<td>CMNET</td>
-
<td>0秒</td>
-
<td>0.007</td>
-
<td>校园4G套餐-400M国内流量</td>
-
<td></td>
-
<td>0.00</td>
-
<td></td>
-
</tr>
-
-
</tbody>
-
</table>
-
<button>导出EXCEL</button>
-
<script src="js/jquery-3.2.1.js"></script>
-
-
<script src="js/jquery.table2excel.js"></script>
-
<script>
-
$('button').click(function(){
-
console.log(1)
-
$("#datatable").table2excel({
-
exclude: ".noExl",
-
name: "Excel Document Name",
-
filename: "myFileName",
-
exclude_img: true,
-
exclude_links: true,
-
exclude_inputs: true
-
});
-
})
-
</script>
-
</body>
-
</html>
https://blog.csdn.net/hefeng6500/article/details/78449436
第一部分:html+js
1.需要使用的表格数据(先不考虑动态生成的table)
<table class="table tableStyles" id="tables"> <caption>不正经的统计表</caption><!--可以生成表格的标题--> <thead> <tr> <th>品牌</th> <th>门店</th> <th>本周回访</th> <th>本月回访</th> <th>总回访</th> <th>本周成交数</th> <th>本月成交数</th> <th>总成交数</th> <th>异常量</th> <th>成交转化率</th> <th>经手人/th> </tr> </thead> <tbody> <tr> <td rowspan="3">华为</td> <td>华为深圳店</td> <td>20</td> <td>80</td> <td>500</td> <td>1</td> <td>3</td> <td>20</td> <td>1</td> <td>4.0%</td> <td>黄生</td> </tr> <tr> <td>华为东莞店</td> <td>20</td> <td>80</td> <td>500</td> <td>1</td> <td>3</td> <td>20</td> <td>1</td> <td>4.0%</td> <td>黄生</td> </tr> <tr> <td>华为佛山店</td> <td>20</td> <td>80</td> <td>500</td> <td>1</td> <td>3</td> <td>20</td> <td>1</td> <td>4.0%</td> <td>黄生</td> </tr> <tr> <td rowspan="3">小米</td> <td>米家深圳店</td> <td>20</td> <td>80</td> <td>500</td> <td>1</td> <td>3</td> <td>20</td> <td>1</td> <td>4.0%</td> <td>林生</td> </tr> </tbody> </table>
2.Js代码
①利用html5的download属性,点击下载该文件
<a id="dlink" style="display:none;"></a> <input type="button" onclick="tableToExcel('tables', 'name', 'myfile.xls')" value="Export to Excel">
<script type="text/javascript"> var tableToExcel = (function () { var uri = 'data:application/vnd.ms-excel;base64,', 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><!--[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>', base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }; return function (table, name, filename) { if (!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } document.getElementById("dlink").href = uri + base64(format(template, ctx)); document.getElementById("dlink").download = filename; document.getElementById("dlink").click(); } })() </script>
②创建ActiveXObject对象复制到表格中
<input id="Button1" type="button" value="导出EXCEL" onclick="javascript:excels('tables')" />
<script type="text/javascript"> var timer; function getExplorer(){//获取浏览器 var explorer=window.navigator.userAgent; if(explorer.indexOf("MSIE") >= 0|| (explorer.indexOf("Windows NT 6.1;") >= 0 && explorer.indexOf("Trident/7.0;") >= 0)){ return 'ie'; }else if (explorer.indexOf("Firefox") >= 0) { return 'Firefox'; }else if(explorer.indexOf("Chrome") >= 0){ return 'Chrome'; }else if(explorer.indexOf("Opera") >= 0){ return 'Opera'; }else if(explorer.indexOf("Safari") >= 0){ return 'Safari'; } } function excels(table){ if(getExplorer()=='ie'){ var curTbl = document.getElementById(table); var oXl=new ActiveXObject("Excel.Application");//创建AX对象excel var oWB = oXL.Workbooks.Add();//获取workbook对象 var xlsheet = oWB.Worksheets(1);//激活当前sheet var sel = document.body.createTextRange(); sel.moveToElementText(curTbl);//把表格中的内容移到TextRange中 sel.select;//全选TextRange中内容 sel.execCommand("Copy");//复制TextRange中内容 xlsheet.Paste();//粘贴到活动的EXCEL中 oXL.Visible = true;//设置excel可见属性 try{ var filename = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls"); }catch(e){ window.print("Nested catch caught " + e); }finally{ oWB.SaveAs(filename); oWB.Close(savechanges = false); oXL.Quit(); oXL = null;//结束excel进程,退出完成 timer = window.setInterval("Cleanup();", 1); } }else{ tableToExcel("tables"); } } function Cleanup(){ window.clearInterval(timer); CollectGarbage();//CollectGarbage,是IE的一个特有属性,用于释放内存的 } var tableToExcel=(function(){ var uri = 'data:application/vnd.ms-excel;base64,', 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><!--[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>', base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }; return function(table, name) { if (!table.nodeType) table = document.getElementById(table); var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}; window.location.href = uri + base64(format(template, ctx)) } })(); </script>
第二部分:分析测试
测试环境(谷歌,火狐,IE,EDGE,QQ浏览器)
①.真正起到作用的是a标签的属性,input按钮只是起到了一个过渡到download属性的作用;
其中有编码解码,需要注意中文乱码情况;
测试只有谷歌和火狐起作用,且只有谷歌下载的文件名是“下载.xls”,火狐的文件名像是编码后的~
双核浏览器当然也只有chrome内核下有效果~~
我比较喜欢的一点,html中合并的单元格导出到excel中继续保留合并效果~~
谷歌截图:
火狐截图:
②.主要是利用AX对象创建excel
在IE下不行,会提示错误“不能使用啥对象什么什么”
难道是需要安装Office软件?没试过。。
这几个浏览器中,谷歌的体验稍微好一点,还可以自己带个命名什么的~~,其他体验都不是很友好~~
还有其他的问题是我继续需要想的,表格内容分页情况导出?筛选条件后导出全部?等等等~
附上源码注释地址:https://github.com/Chuyue0/javascript-demo/blob/master/tableExporeExcel.html
开发过程中有很多预料不到的事,继续加油吧!
~~~~~~~~~~~~剩到最后的解决办法是利用插件~~~~~~~~~~~~
比如github上的
1020 Star:https://github.com/kayalshri/tableExport.jquery.plugin
270 Star:https://github.com/clarketm/TableExport
159 Star:https://github.com/huanz/tableExport
说明一下,星星多的插件是有base64编码,所以还额外需要js脚本!
个人比较喜欢最少星星的库,感觉明了清晰,可以按需加载~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
js实现table导出Excel,保留table样式
浏览器环境:谷歌浏览器
1.在导出Excel的时候,保存table的样式,有2种方法,①是在table的行内写style样式,②是在模板里面添加样式
2.第一种方式:行内添加样式
<td style="font-size: 18px">公司一</td>
效果:
完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table td { font-size: 12px; width: 200px; height: 30px; text-align: center; background-color: #4f891e; color: #ffffff; } </style> </head> <body> <a download="table导出Excel" id="excelOut" href="#">table导出Excel</a> <table cellspacing="0" cellpadding="0" border="1" id="tableToExcel"> <thead> <tr> <td style="font-size: 18px">公司一</td> <td>公司二一</td> <td>公司三</td> </tr> </thead> <tbody> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td colspan="3">共计</td> </tr> </tbody> </table> <script> window.onload = function () { tableToExcel('tableToExcel', '下载模板') }; //base64转码 var base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }; //替换table数据和worksheet名字 var format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); } function tableToExcel(tableid, sheetName) { var uri = 'data:application/vnd.ms-excel;base64,'; var 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><!--[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]-->' + ' <style type="text/css">' + 'table td {' + 'border: 1px solid #000000;' + 'width: 200px;' + 'height: 30px;' + ' text-align: center;' + '' + 'color: #ffffff;' + ' }' + '</style>' + '</head><body ><table class="excelTable">{table}</table></body></html>'; if (!tableid.nodeType) tableid = document.getElementById(tableid); var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML}; document.getElementById("excelOut").href = uri + base64(format(template, ctx)); } </script> </body> </html>
3.第二种方式:在模板里面里面添加样式
在这里面添加的样式excel就能找到和识别了
var 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><!--[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]-->' + ' <style type="text/css">' + 'table td {' + 'border: 1px solid #000000;' + 'width: 200px;' + 'height: 30px;' + ' text-align: center;' + '' + 'color: #ffffff;' + ' }' + '</style>' + '</head><body ><table class="excelTable">{table}</table></body></html>';
完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table td { font-size: 12px; width: 200px; height: 30px; text-align: center; background-color: #4f891e; color: #ffffff; } </style> </head> <body> <a download="table导出Excel" id="excelOut" href="#">table导出Excel</a> <table cellspacing="0" cellpadding="0" border="1" id="tableToExcel"> <thead> <tr> <td >公司一</td> <td>公司二一</td> <td>公司三</td> </tr> </thead> <tbody> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td>A公司</td> <td>B公司</td> <td>C公司</td> </tr> <tr> <td colspan="3">共计</td> </tr> </tbody> </table> <script> window.onload = function () { tableToExcel('tableToExcel', '下载模板') }; //base64转码 var base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }; //替换table数据和worksheet名字 var format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); } function tableToExcel(tableid, sheetName) { var uri = 'data:application/vnd.ms-excel;base64,'; var 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><!--[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]-->' + ' <style type="text/css">' + 'table td {' + 'border: 1px solid #000000;' + 'width: 200px;' + 'height: 30px;' + ' text-align: center;' + '' + 'color: #ffffff;' + ' }' + '</style>' + '</head><body ><table class="excelTable">{table}</table></body></html>'; if (!tableid.nodeType) tableid = document.getElementById(tableid); var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML}; document.getElementById("excelOut").href = uri + base64(format(template, ctx)); } </script> </body> </html>
注意:如果同时添加了行内样式和模板样式,行内的样式会覆盖模板的样式
大佬!我们怎么变成是html格式的呢!导出的并不是excel格式
!你是不是下载的时候没有设置文件的后缀?
a标签的download="table导出Exce.xls"
如<a download="table导出Exce.xls" id="excelOut" href="#">table导出Excel</a>
问题一 如果没有安装 office 导出来
安装 office 就默认指定了后缀
问题二 文件格式和扩展名不匹配。文件可能已损坏或不安全 除非您信任其来源
没解决 不影响功能
office 打开报 文件格式和扩展名不匹配。文件可能已损坏或不安全 除非您信任来源 否则请勿打开,是否仍要打开它