Skip to content

Instantly share code, notes, and snippets.

@FrankFan
Created January 19, 2021 07:27
Show Gist options
  • Save FrankFan/f6f42b381897ed12b172cee1701e9e9a to your computer and use it in GitHub Desktop.
Save FrankFan/f6f42b381897ed12b172cee1701e9e9a to your computer and use it in GitHub Desktop.
/**
* 导出csv文件
* @see https://gist.github.com/dannypule/48418b4cd8223104c6c92e3016fc0f61
*/
class json2csv {
exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
const jsonObject = JSON.stringify(items);
let csv = this.convertToCSV(jsonObject);
const exportedFilenmae = fileTitle + '.csv' || 'export.csv';
// 重要!为了解决CSV中文乱码问题
// @see https://huangwang.github.io/2019/08/27/客户端使用JS导出CSV文件及中文乱码问题解决方案/
csv = '\ufeff' + csv;
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// feature detection
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ',';
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
}
export default new json2csv();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment