First understand the csv format file,
- CSV is Comma-Separated Values (CSV). Its file stores tabular data (numbers and text) in plain text form. Each line of the file is a data record.
- Each record consists of one or more fields, separated by commas.
- The use of commas as field separators is where the name of this file format comes from, because the delimiting character can also be other than a comma, sometimes called character-separated values.
- By default, CSV files use English commas as column separators and newline characters as row separators.
- If you do not provide a web page and only use the command line or binary program to output data to CSV, you only need to split the data segments by , and the rows by \n, and write it to a .csv file.
js implementation
/**
* @description 纯前端实现将表格数据导出为csv格式文件
* @param {Array} headers 表格头配置项,headers中的key值与data中每一个item的属性名一一对应
* @param {Array} data 表格数据
* @param {String} fileName 导出的文件名称
*/
function downloadCsv(header, data, fileName = "导出结果.csv") {
if (!header || !data|| !Array.isArray(header) || !Array.isArray(data) || !header.length || !data.length) {
return;
}
var csvContent = 'data:text/csv;charset=utf-8,\ufeff';
const _header = header.map(h => h.title).join(",");
const keys = header.map(item => item.key);
csvContent += _header + '\n';
data.forEach((item, index) => {
let dataString = '';
for (let i = 0; i < keys.length; i++) {
dataString += item[keys[i]] + ',';
}
csvContent += index < data.length ? dataString.replace(/,$/, '\n') : dataString.replace(/,$/, '');
});
const a = document.createElement('a');
a.href = encodeURI(csvContent);
a.download = fileName;
a.click();
window.URL.revokeObjectURL(csvContent);
}
Usage example
let header = [
{
key: "order", title: "序号" },
{
key: "name", title: "姓名" },
{
key: "age", title: "年龄" },
{
key: "height", title: "身高" },
{
key: "address", title: "地址" },
],
data = [
{
order: 1,
name: "Abby",
age: 23,
height: 168,
address: "北京,中关村",
},
{
order: 2,
name: "Leo",
age: 28,
height: 183,
address: "上海,陆家嘴",
},
{
order: 3,
name: "Alen",
age: 35,
height: 178,
address: "深圳,南山区",
},
{
order: 4,
name: "Daisy",
age: 27,
height: 160,
address: "广州,天河区",
},
];
downloadCsv(header, data, "人员信息表");
The result is as follows:
Note: If the table content is comma-delimited, be sure to enclose the content in double quotes, otherwise the content of the same cell will be separated into multiple columns during export.