Update:
Here is slightly better way to do it:
- Open up command prompt in the directory of your project.
- Install file-saver by typing
npm install --save file-saver
import { saveAs } from 'file-saver';
into your .ts file.- Here is the updated code based on the new import.
downloadFile(data: any) {
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(data[0]);
let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
let csvArray = csv.join('\r\n');
var blob = new Blob([csvArray], {type: 'text/csv' })
saveAs(blob, "myFile.csv");
}
Credits to this answer for converting an object to CSV.
Here is the method to use:
downloadFile(data: any) {
const replacer = (key, value) => (value === null ? '' : value); // specify how you want to handle null values here
const header = Object.keys(data[0]);
const csv = data.map((row) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(',')
);
csv.unshift(header.join(','));
const csvArray = csv.join('\r\n');
const a = document.createElement('a');
const blob = new Blob([csvArray], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myFile.csv';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
I’ll add on later if I found a better way to do it.