【发布时间】:2016-08-28 10:38:07
【问题描述】:
我需要一些将我的 html 表导出为 excel 文件的函数。以下代码执行此操作,但它将表格保存在错误的字符集中。我需要将其设为 UTF-8。
这是我的代码:
function exceller() { //UI
var uri = 'data:application/vnd.ms-excel;base64; charset=UTF-8,',
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];
});
};
table = document.getElementById("pztable");
$('#toExcel').html($(table).html());
$('#toExcel').find("thead > tr > th:last-child").remove();
$('#toExcel').find("tbody > tr > td:last-child").remove();
var toExcel = $('#toExcel').html();
var ctx = {
worksheet: name || 'Worksheet',
table: toExcel
};
$('#toExcel').remove();
window.open(uri + base64(format(template, ctx)));
}
注意:我的真实表的 id 是“pztable”,但我正在删除它的最后一列,因为我不想导出该列。所以我正在创建一个 id="toExcel" 的表,然后我正在导出该表。
【问题讨论】:
标签: javascript excel utf-8 html-table export-to-excel