您的位置:首页 > Web前端 > JavaScript

js table数据导出excel文件

2018-03-05 15:35 2751 查看

前言

百度了几篇有关的教程,都差不多甚至可以说是完全相同;在这里也只是精简、记录一下。


代码

表格转换成excel并下载

(document).ready(function () {(document).ready(function () {(“#myBtn”).click(function () { //点击下载按钮,执行方法

CreateExcel(“myTable”,”test”);

});

});

//将table导出到excel

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 CreateExcel(tableid,fileName) {

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(fileName + “.xls”, //文件名和文件格式 但尝试改了一下fileName 这里并不影响

“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,fileName) //调用tableToExcex table的id 和 要生成的文件名 }

}

function Cleanup() {

window.clearInterval(idTmr);

Co
4000
llectGarbage();

}

var tableToExcel = (function () {

var uri = ‘data:application/vnd.ms-excel;base64,’,

template =


{table}
’,

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))

a = document.createElement(“a”);

a.download = name;

a.href = uri + base64(format(template, ctx));

document.body.appendChild(a);

a.click();

document.body.removeChild(a);

}

})()

下载/Download excel

上下文表格布局
产品付款日期状态
产品123/11/2013待发货
产品210/11/2013发货中
产品320/10/2013待确认
产品420/10/2013已退货

结束

对于段代码,也不是太理解,需要更熟练的应用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: