- 使用 papaparse 导出的csv数据,用excel打开中文出现乱码
import Papa from "papaparse";
后台接口返回来的数据
const resStr = response;
let fileName = "XXXX文件";
const data = Papa.parse(resStr);
// Convert back to CSV
const csv = Papa.unparse(data);
//定义文件内容,类型必须为Blob 否则createObjectURL会报错
let content = new Blob(["\ufeff" + csv], {
// add "\ufeff" ES5新增的空白符 【字节次序标记字符】Byte Order Mark,简称BOM
type:
".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
});
//生成url对象
let urlObject = window.URL || window.webkitURL || window;
let url = urlObject.createObjectURL(content);
//生成<a></a>DOM元素
let el = document.createElement("a");
//链接赋值
el.href = url;
if (this.startTime != "" && this.endTime != "") {
fileName = this.startTime + "-" + this.endTime + fileName;
}
el.download = fileName + ".csv";
//必须点击否则不会下载
el.click();
//移除链接释放资源
urlObject.revokeObjectURL(url);
解释:
主要增加在Blob中添加了 "\ufeff"。 ES5新增的空白符 【字节次序标记字符】Byte Order Mark,简称BOM
网友评论