我有以下函数将html导出为excel:
function generateexcel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
一个问题是数据中的特殊字符会转换为其他符号:
你会如何解决这个问题?是否有任何字符替换为html以防止它?任何编码选项?
答案 0 :(得分:8)
替换字符是一个糟糕的解决方案。
我替换了encodeURIComponent for escape并且工作正常,但是自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
“Base64编码/解码已经是现代(tm)浏览器中的本机函数:btoa(str)和atob(str)是应该可以在没有任何外部重新实现的情况下使用的函数。” - chipairon
答案 1 :(得分:4)
已解决为有问题的符号添加替换:
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));
}
答案 2 :(得分:3)
我有同样的问题,只需将encodeURIComponent替换为escape。
function generateexcel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel,' + escape(html));
}
对我有用......
答案 3 :(得分:2)
只需将encodeURIComponent
替换为escape
。
答案 4 :(得分:0)
在我的情况下,我使用之前发布的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));
}
希望它有所帮助...