I know this is a question already answered but couldn't find the solution that works for me.
I've a HTML button that, when clicked, generate an array of objects in typescript(which basically javascript) and i want to generate a csv file that will be downloaded.
Here is the example of the javascript array of objects:
var items = [
{ "name": "Item 1", "color": "Green", "size": "X-Large" },
{ "name": "Item 2", "color": "Green", "size": "X-Large" },
{ "name": "Item 3", "color": "Green", "size": "X-Large" }];
// Loop the array of objects
for(let row = 0; row < items.length; row++){
let keysAmount = Object.keys(items[row]).length
let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
keysCounter++
}
}
keysCounter = 0
}
console.log(csv)
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'people.csv';
hiddenElement.click();
I tried this example code but in my case it create the csv file, but doesn't insert the csv string correctly in the csv file, the csv string is has rows of element separated by a comma and each row is determined by a new line, but here all the data of each row sits in one cell of the csv file, how can I make so that each value of each row sits in a different cell?
here is the csv string that it:
name,color,size
Item 2,Green,X-Large
Item 3,Green,X-Large
this.ConvertToCSV(data)
is a custom function that you made? Can you show us what it does? – OlimpiaolinConvertToCSV
? what does its output look like? – Colungaconsole.log
why not exclude the rest of the download code from the question? It seems irrelevant. – Tony