https://www.jq22.com/webqd5420
ID | 姓名 | 年龄 |
0001 | 张三 | 24 |
ID | 姓名 | 年龄 |
0002 | 李四 | 24 |
ID | 姓名 | 年龄 |
0003 | 王五 | 24 |
#tabDiv1,#tabDiv2,#tabDiv3 {
border:1px solid pink;
margin:10px auto;
width:100%;
}
button {
width:100%;
}
function exp() {
tablesToExcel(['tabDiv1', 'tabDiv2', 'tabDiv3'], ['yy', 'bb', 'cc'], "abc.xls", "Excel");
}
//导出excel包含多个sheet
//tables:tableId的数组;wsbames:sheet的名字数组;wbname:工作簿名字;appname:Excel
function tablesToExcel(tables, wsnames, wbname, appname) {
var uri = 'data:application/vnd.ms-excel;base64,',
tmplWorkbookXML = '
'
'
'' +
'' +
'' +
'{worksheets}',
tmplWorksheetXML = '{rows}
tmplCellXML = '
base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
}
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType)
tables[i] = document.getElementById(tables[i]);
// 控制要导出的行数
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += '
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
ctx = {
attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : '',
nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
data: (dataFormula) ? '' : dataValue,
attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += ''
}
ctx = {
rows: rowsXML,
nameWS: wsnames[i] || 'Sheet' + i
};
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {
created: (new Date()).getTime(),
worksheets: worksheetsXML
};
workbookXML = format(tmplWorkbookXML, ctx);
// 查看后台的打印输出
//console.log(workbookXML);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}