<div id="download" >Download CSV</div>
#download {
display: inline-block;
padding: 16px;
font-family: 'Arial';
font-size: 20px;
cursor: pointer;
border: 1px solid #ddd;
border-radius: 5px;
background: #efefef;
}
View Compiled
const downCsv = document.querySelector("#download");
const csvData = [
["id", "name", "message"],
{
id: 1,
name: "Mandy",
message: "hello\nworld"
},
{
id: 2,
name: "Mars",
message: "hello JS"
}
];
downCsv.addEventListener("click", () => {
const newData = csvData
.filter((e, i) => i !== 0)
.map((e) => {
return Object.keys(e).reduce((acc, curr) => {
return { acc, { [curr]: '"' + e[curr] + '"' } };
}, {});
});
console.log(newData)
exportFile(newData);
});
const exportFile = ( rows, fileTitle) => {
const jsonObject = JSON.stringify(rows);
const csv = '\ufeff' + convertToCSV(jsonObject); // support Chinese
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', fileTitle || 'data.csv');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
const toCsv = objArray => {
const array =
typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
const newData = array.map(e => {
console.log('array', e)
const str = Object.entries(e).reduce((arr, [k,v], i) => {
return [arr, v];
}, []);
return str.join(',') + '\r\n';
})
return newData.join('');
}
/* CSV: convert json to json */
const convertToCSV = (objArray) => {
const array =
typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
let str = '';
console.log('aa', array);
for (let i = 0; i < array.length; i++) {
let line = '';
Object.entries(array[i]).forEach(([key, value]) => {
if (line !== '') {
line += ',';
}
line += value;
});
str += line + '\r\n';
console.log('TT', str)
}
console.log('bb', str);
return str;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.