我需要一些将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”的表,然后我将导出该表。
答案 0 :(得分:1)
我解决了这个问题。 这是代码的最后一个版本。
function exceller() { //UI
var uri = 'data:application/vnd.ms-excel;base64,'
, 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 version="1.0" encoding="UTF-8" standalone="yes"?><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 || '',
table: toExcel
};
$('#toExcel').remove();
window.open(uri + base64(format(template, ctx)));
}