1. 程式人生 > >js table資料匯出excel檔案

js table資料匯出excel檔案

前言

百度了幾篇有關的教程,都差不多甚至可以說是完全相同;在這裡也只是精簡、記錄一下。

程式碼




表格轉換成excel並下載


(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);
CollectGarbage();
}
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

上下文表格佈局
產品 付款日期 狀態
產品1 23/11/2013 待發貨
產品2 10/11/2013 發貨中
產品3 20/10/2013 待確認
產品4 20/10/2013 已退貨

結束

對於段程式碼,也不是太理解,需要更熟練的應用