Sometimes it is necessary to export some data to an Excel file and download it. Encountered this problem, in fact, you can directly export a CSV (Comma-Separated Values) file. CSV is a table file stored in plain text. The data in each cell is separated by a comma, and each row is separated by a newline character, similar to this form:
name,age,from\n
suyan,20,beijing\n
lefex,30,baotou\n
Therefore, if you export some data to a file, you only need to convert it to this data format.
{
header: ["name", "age", "from"],
data: [
{
name: "suyan",
age: "23",
from: 'beijing'
},
{
name: "lefex",
age: "30",
from: 'baotou'
}
]
}
To convert this object into a CSV string, the code is as follows:
function exportToCSVFile(obj) {
let header = obj.header.join(',') + '\n';
let datas = obj.data.map(ele => {
return `${ele.name},${ele.age},${ele.from}\n`;
});
let dataStrs = [header, ...datas].join('');
}
function exportToCSVFile(obj) {
let header = obj.header.join(',') + '\n';
let datas = obj.data.map(ele => {
return `${ele.name},${ele.age},${ele.from}\n`;
});
let dataStrs = [header, ...datas].join('');
// 创建一个 Blob 对象
const blob = new Blob(['\uFEFF' + dataStrs], {
type: 'text/plain;charset=utf-8',
});
// 创建一个 a 标签
const link = document.createElement("a");
// 一个 URL,可以是任意协议的,不只是 HTTP 协议
// 这里创建了一个 Blob URL
// blob:http://localhost:1234/9b3be48e-9948-496d-8a2b-18d437eb46e0
link.href = URL.createObjectURL(blob);
console.log(link.href);
// 此属性表示用户下载文件而不是进行导航到 URL,这里指的为文件名
link.download = "suyan.csv";
link.click();
// 需要释放 URL
URL.revokeObjectURL(link.href);
}