前端使用application/vnd.ms-excel导出Excel非拉丁字符乱码如何解决
导出Excel非拉丁字符乱码修复方案
问题原因
当前代码仅在适配IE的分支添加了UTF-8 BOM标识,现代浏览器分支直接拼接未做UTF-8编码的HTML内容到data URI,Excel无法识别非默认编码的阿拉伯语等非拉丁字符,就会出现乱码。
修复后的完整代码
function exportTableToExcel(tableID, filename = ''){ var dataType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; var input = document.getElementById(tableID); var tableSelect = input.cloneNode(true); const thead = document.createElement("thead"); thead.innerHTML =` <tr><th>Name</th><th>Skills</th></tr> ` tableSelect.prepend(thead); var tableHTML = tableSelect.outerHTML; // 统一添加UTF-8 BOM头,保证所有场景下Excel可识别非拉丁字符 const blob = new Blob(['\ufeff', tableHTML], { type: dataType }); // 统一文件名处理 filename = filename?filename+'.xlsx':'excel_data.xlsx'; // 兼容所有浏览器的下载逻辑 if (navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, filename); } else { const downloadLink = document.createElement("a"); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = filename; document.body.appendChild(downloadLink); downloadLink.click(); // 释放内存避免泄漏 setTimeout(() => { document.body.removeChild(downloadLink); window.URL.revokeObjectURL(downloadLink.href); }, 100); } }
关键修改点
- 移除了易出现编码问题的手动拼接data URI逻辑,所有浏览器分支统一使用带BOM头的Blob生成下载资源
- 用
URL.createObjectURL处理Blob生成下载链接,自动适配UTF-8编码,不会丢失非拉丁字符的编码信息 - 新增下载链接的内存释放逻辑,避免页面长期运行出现内存占用过高的问题
内容的提问来源于stack exchange,提问作者Hasan A Yousef
相关产品推荐
相关产品推荐

