將表格匯出成 Excel 時,舊版 IE 可利用 execCommand 的 SaveAs 功能;其他瀏覽器則可將 HTML 轉成 data URI,讓使用者下載或開啟。
實作前應先確認表格存在,並注意資料量與欄位格式,避免匯出後亂碼或格式跑掉。
function toExcel(tableId) {
var table = document.getElementById(tableId);
if (!table) {
alert('你要導出的表不存在!');
return;
}
var html = table.outerHTML;
if ($.browser.msie) {
var win = window.open('', '_blank');
win.document.write(html);
win.document.close();
win.document.execCommand('Saveas', true, 'export.xls');
win.close();
} else {
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
}