Javascript table 导出到 excel utf8

Javascript table export to excel utf8

我需要一些将 html table 导出为 excel 文件的功能。以下代码执行此操作,但它会将 table 保存在错误的字符集中。我需要将其设为 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)));
}

注意:我真正的 table 的 ID 是 "pztable" 但我要删除它的最后一列,因为我不想导出该列。所以我用 id="toExcel" 创建一个 table 然后我导出那个 table.

我解决了这个问题。 这里是最后一版的代码是。

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