HTML表导出到Excel utf-8字符错误

时间:2016-06-04 13:20:11

标签: angularjs excel export excel-2010 export-to-excel

我有以下html(基于角度js所以它可能有一些角度标签) https://gist.github.com/sudarshann/668ba8d3dda02da366f59af2bcc3187a

我试图使用以下代码转换为xls导出

var date = new Date();
var fileName = "Resumos " + tabName + " " + date + ".xls";
var fileRaw = document.getElementById(id).innerHTML;
fileRaw = fileRaw.split("↑").join("");
var file = fileRaw.split("↓").join("");

var blob = new Blob([file], {
   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;"
});
saveAs(blob, fileName);

我在Excel文件中获得的结果(使用MS Office 2016打开)

https://www.dropbox.com/s/yyqowtzebaet7xl/error.jpg?dl=0

1 个答案:

答案 0 :(得分:0)

此代码最终解决了我的编码问题。

        var date = new Date();
        var sheetName = "BASE DE CONCESSIONÁRIAS " + date;
        var fileName = sheetName + ".xls";
        var fileRaw = document.getElementById(id).innerHTML;
        fileRaw = fileRaw.split("↑").join("");
        var file = fileRaw.split("↓").join("");
        $log.info("here ", file);

          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:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{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]; }) }

            var toExcel = file;
            var ctx = {
                worksheet: sheetName || '',
                table: toExcel
            };

            var link = document.createElement('a');
            link.download = fileName;
            link.href = uri + base64(format(template, ctx));
            link.click();
PS:我仍然不确定为什么这会解决问题或者这有什么不同。如果有人可以解释我的工作方式和原因,而不是问题中的代码

,那将是很好的