导出html表格到Excel javascript函数特殊字符改变了

我有以下function,出口到Excel的HTML:

function generateexcel(tableid) { var table= document.getElementById(tableid); var html = table.outerHTML; window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html)); } 

一个问题是数据中的特殊字符被转换为其他符号:

  • 1º=1º
  • é=Ã

你将如何解决这个问题? 有没有任何字符replace为了防止它的HTML? 任何编码选项?

更换字符是一个不好的解决scheme。

我用escapeURLreplace了escapeURL,并且工作正常,但是自从ECMAScript v3以来,escape已经被弃用了。

出现此问题是因为encodeURIComponent使用UTF-8而Excel不使用。

更好的方式给我。

将数据编码到base64并像这样导出。 我使用了https://github.com/carlo/jquery-base64/blob/master/jquery.base64.min.js中的 jquery-base64插件

并将代码更改为:

 window.open('data:application/vnd.ms-excel;base64,' + $.base64.encode(html)); 

如果你不想使用jquery,你可以使用这个base64_encode函数http://phpjs.org/functions/base64_encode

“在现代(tm)浏览器中,Base64编码/解码已经是本地function:btoa(str)和atob(str)是应该可以在没有任何外部重新实现的情况下使用的function。 – chipairon

解决了添加replace有问题的符号:

 function generateexcel(tableid) { var table= document.getElementById(tableid); var html = table.outerHTML; //add more symbols if needed... while (html.indexOf('á') != -1) html = html.replace('á', 'á'); while (html.indexOf('é') != -1) html = html.replace('é', 'é'); while (html.indexOf('í') != -1) html = html.replace('í', 'í'); while (html.indexOf('ó') != -1) html = html.replace('ó', 'ó'); while (html.indexOf('ú') != -1) html = html.replace('ú', 'ú'); while (html.indexOf('º') != -1) html = html.replace('º', 'º'); window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html)); } 

我有同样的问题,只需要replaceencodeURIComponent进行转义。

 function generateexcel(tableid) { var table= document.getElementById(tableid); var html = table.outerHTML; window.open('data:application/vnd.ms-excel,' + escape(html)); } 

这个对我有用…

只需用escapereplaceencodeURIComponent

在我的情况下,我使用之前发布的generateexcel函数,只是添加特殊字符的大写字母,以使其工作

  function generateexcel(tableid) { var table= document.getElementById(tableid); var html = table.outerHTML; while (html.indexOf('á') != -1) html = html.replace('á', 'á'); while (html.indexOf('Á') != -1) html = html.replace('Á', 'Á'); while (html.indexOf('é') != -1) html = html.replace('é', 'é'); while (html.indexOf('É') != -1) html = html.replace('É', 'É'); while (html.indexOf('í') != -1) html = html.replace('í', 'í'); while (html.indexOf('Í') != -1) html = html.replace('Í', 'Í'); while (html.indexOf('ó') != -1) html = html.replace('ó', 'ó'); while (html.indexOf('Ó') != -1) html = html.replace('Ó', 'Ó'); while (html.indexOf('ú') != -1) html = html.replace('ú', 'ú'); while (html.indexOf('Ú') != -1) html = html.replace('Ú', 'Ú'); while (html.indexOf('º') != -1) html = html.replace('º', 'º'); while (html.indexOf('ñ') != -1) html = html.replace('ñ', 'ñ'); while (html.indexOf('Ñ') != -1) html = html.replace('Ñ', 'Ñ'); window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html)); } 

希望能帮助到你…