如果没有自己做过或者看过,10年经验的程序员都能质疑前端能做下载功能吗?话不多说,拿去直接用
csvSeparator = ',';
/**
* @param value
* //[
* {'userId':'weiweliu','creationDate':'1575014176000', 'lastModifiedDate', 'triggerTime'},
* {'userId':'weiweliu','creationDate':'1575014176000', 'lastModifiedDate', 'triggerTime'}
* ]
* @param columns //['userId', 'creationDate', 'lastModifiedDate', 'triggerTime']
* @param exportFilename // 'Usage-Report'
*/
exportCSV(value, columns, exportFilename) {
const data = value;
let csv = '\ufeff'; //设置解码格式,不设置会导致在excel中打开乱码
// headers
for (let i = 0; i < columns.length; i++) {
const column = columns[i];
csv += '"' + (column.header || column) + '"';
if (i < (columns.length - 1)) {
csv += this.csvSeparator;
}
}
// body
data.forEach((record) => {
csv += '\n';
for (let i_1 = 0; i_1 < columns.length; i_1++) {
const column = columns[i_1];
csv += '"' + this.resolveFieldData(record, column) + '"';
if (i_1 < (columns.length - 1)) {
csv += this.csvSeparator;
}
}
});
const blob = new Blob([csv], {
type: 'text/csv;charset=utf-8;'
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, exportFilename + '.csv');
} else {
const link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
if (link.download !== undefined) {
link.setAttribute('href', URL.createObjectURL(blob));
link.setAttribute('download', exportFilename);
link.click();
} else {
csv = 'data:text/csv;charset=utf-8,' + csv;
window.open(encodeURI(csv));
}
document.body.removeChild(link);
}
}