Here is the working code to download a csv file in vue
This sample code converts array of objects to perfect csv file with headers
call the function exportCSVFile(headers, items, fileTitle)
headers = {
name: 'Name' // formatted column name,
age: 'Age'
}
items = [
{
name: 'Joo',
age: 21
},
{
name: 'ant',
age: 20
}
]
filename = 'somefilename.csv'
function convertToCSV(objArray) {
const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
let str = '';
for (let i = 0; i < array.length; i++) { // eslint-disable-line
let line = '';
for (const index in array[i]) { // eslint-disable-line
if (line !== '') line += ',';
line += array[i][index];
}
str += line + '\r\n'; // eslint-disable-line
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
const jsonObject = JSON.stringify(items);
const csv = convertToCSV(jsonObject);
const exportedFilenmae = fileTitle + '.csv' || 'export.csv'; // eslint-disable-line
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) {
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);
}
}
}
export default exportCSVFile;
If the given value is 2d array, just use this function
function downloadCSVData () {
var array = [
[1,2,3],
[4,5,6],
[7,8,9]
];
var str = '';
for (var i = 0; i < array.length; i++) {
let line = '';
line = array[i].join(",");
str += line + '\r\n';
}
var blob = new Blob([str], { type: 'text/csv;charset=utf-8;' });
var link = document.createElement('a');
var url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', 'csvfilename.csv');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}