I have a field called csvdata
that contains an array of the following format:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
I'm trying to download a CSV file of this data. I'm using Vue so it looks like:
<button type="button" class="btn btn-info action_btn" v-on:click="downloadCSVData">
Download
</button>
How should the downloadCSVData
function look like?
I have a field called csvdata
that contains an array of the following format:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
I'm trying to download a CSV file of this data. I'm using Vue so it looks like:
<button type="button" class="btn btn-info action_btn" v-on:click="downloadCSVData">
Download
</button>
How should the downloadCSVData
function look like?
- you need a backend scripting language such as PHP to process that array into a downloadable file. – Oliver M Grech Commented Oct 8, 2019 at 19:26
3 Answers
Reset to default 28I think you can create a method like so, assuming csvdata
is a data property accessible by this
in your Vue component:
downloadCSVData() => {
let csv = 'Put,Column,Titles,Here\n';
this.csvdata.forEach((row) => {
csv += row.join(',');
csv += "\n";
});
const anchor = document.createElement('a');
anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
anchor.target = '_blank';
anchor.download = 'nameYourFileHere.csv';
anchor.click();
}
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);
}
- Convert the Array to text. (
let data = [[1,2,3], [4,5,6], [7,8,9]].join('\r\n').toString()
) - Convert the text to base64. (
let encoded_data = btoa(data)
) - Create an iFrame and set its src = the encoded data.
let iframe = document.createElement('iframe'); iframe.src = "data:application/octet-stream;base64," + encoded_data
- Append the iframe to the document's body:
document.body.appendChild(iframe)
.
There's some drawbacks to this approach though:
- Content Security Policy can block step 4. You have control over CSP in your page, but don't sacrifice security for easy code.
- The file will always be named "download" with no file extension.
A better approach would be to create a temporary file on the server and provide the user a link to that file.