用html导出html表到excel时unicode数据出现问题

时间:2019-07-07 15:52:24

标签: javascript excel html-table

我想将html表导出为ex​​cel,它可以工作,但有时其中的阿拉伯或波斯数据被转换为如下形式:

ع©ط§ط±ط¨ط± ط«ط¨طھ ع©ظ†ظ†ط¯ظ‡

我使用以下代码:

var tableText = `<table><thead><tr><th colspan="5">یک عنوان در فارسی</th></tr><tr>`;
.
.
.
adding <th>s and <tbody> and <td>s
.
.
.
tableText += "</tbody></table>";
      var downloadLink = document.createElement("a");
      var uri = 'data:application/vnd.ms-excel,' + encodeURIComponent(tableText);
      downloadLink.href = uri;
      var filename = "some file name";
      downloadLink.download = filename + ".xls";

      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);

它会下载excel文件,看起来就像下面的图片在下载的excel文件中一样:

enter image description here

1 个答案:

答案 0 :(得分:0)

我在链接中找到了解决方案: Encoding UTF-8 when exporting HTML table to Excel

它可以正常工作,我的所有unicode数据都正确保存在excel文件中。但是我做了一些更改,因为我想使用给定的文件名,然后使用锚标记而不是window.open,该标记会动态添加到文档中,并在单击后将被删除。然后如下图所示:

function exportExcel(tableText, filename, worksheetName) {
        let downloadLink = document.createElement("a");
        let 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"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><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>' + tableText + '</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]; }) }

        let ctx = { worksheet: worksheetName || 'Worksheet', table: tableText }
        // window.location.href = uri + base64(format(template, ctx));
        downloadLink.href = uri + base64(format(template, ctx));
        downloadLink.download = (filename||"exportedTable") + ".xls";

        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    }

最后,您可以使用数据调用此函数:

exportExcel(anyHtmlTableText, "myFileName","mySheetName");