Download CSV
unknown
javascript
2 years ago
1.9 kB
7
Indexable
// this method validates the data and creates the csv file to download downloadCSVFile() { let rowEnd = '\n'; let csvString = ''; let rowData = new Set(); this.documentList.forEach(function (record) { Object.keys(record).forEach(function (key) { rowData.add(key); }); }); rowData = Array.from(rowData); // splitting using ',' csvString += rowData.join(','); csvString += rowEnd; // main for loop to get the data based on key value for(let i=0; i < this.documentList.length; i++){ let colValue = 0; for(let key in rowData) { if(rowData.hasOwnProperty(key)) { let rowKey = rowData[key]; if(colValue > 0){ csvString += ','; } // If the column is undefined, it as blank in the CSV file. let value = this.documentList[i][rowKey] === undefined ? '' : this.documentList[i][rowKey]; csvString += '"'+ value +'"'; colValue++; } } csvString += rowEnd; } let downloadElement = document.createElement('a'); // This encodeURI encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters). downloadElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvString); downloadElement.target = '_self'; // CSV File Name downloadElement.download = 'PDD Data.csv'; // below statement is required if you are using firefox browser document.body.appendChild(downloadElement); // click() Javascript function to download CSV file downloadElement.click(); }
Editor is loading...
Leave a Comment