我已经包含以下功能来获取数据表并将其导出到各种互联网资源的Excel表格中。它适用于英文字符,但当表格包含中文字母时,excel文档显示随机字符而不是中文字符。这与excel V中的编码有关吗?我的页面?我该如何解决这个问题?
function exportToExcel(table, name)
{
var uri = 'data:application/vnd.ms-excel;base64,';//application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
var 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>';
if(!table.nodeType)
table = document.getElementById(table);
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
uri += toBase64(format(template, ctx));
//window.location.href = uri;
var dlLink = document.createElement('a');
if (typeof dlLink.download === 'string') {
document.body.appendChild(dlLink); // Firefox requires the link to be in the body
dlLink.download = outputFile;
dlLink.href = uri;
dlLink.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
function toBase64(data)
{
if (window.btoa)
return window.btoa(unescape(encodeURIComponent(data)));
else // IE
{
var strUni = data;
var strUtf = strUni.replace(/[\u0080-\u07ff]/g,
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xc0 | cc >> 6, 0x80 | cc & 0x3f);
})
.replace(/[\u0800-\uffff]/g,
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f);
});
return strUtf;
}
}
function format(template, ctx)
{
return template.replace(/{(\w+)}/g, function(m, p) { return ctx[p]; });
}
答案 0 :(得分:0)
我在模板字符串中添加了head标签,这告诉excel将文件打开为UTF-8。这保留了excel中的中文字符。