Reputation: 115
I'm trying to export my json to xlsx. I'm able to export it but, not getting the right format in excel file.
Here is my code :
downloadFile() {
let Obj = {
"data": [12,123],
"date": ["2018-10-10","2018-02-10"]
}
const items = [];
items['data'] = Obj.data;
items['date'] = Obj.date;
const header = Object.keys(items);
let csv;
header.map((data)=>{
csv = this.items[data];
});
csv.unshift(header.join(','))
let csvArray = csv.join('\r\n');
var blob = new Blob([csvArray], { type: 'text/csv' })
FileSaver.saveAs(blob, "filename" + ".xlsx");
}
O/p I'm getting : ["Data, Date","2018-10-10","2018-02-10"]
I'm not able to render date values in excel
Screenshot of my exported excel file :
Upvotes: 0
Views: 3128
Reputation: 5066
You need something like below. In order to have data in one column and date in one column you will have to structure the data in a way that when arranged in columns it appears as you want it. Below is a sample you can try to download this will work as expected. A simpler solution will be creating a hidden html table with the data with the similar structure as you want to export and then convert that to CSV.
function downloadFile() {
let Obj = {
"data": [12, 123],
"date": ["2018-10-10", "2018-02-10"]
}
const items = [];
items[0] = Object.keys(Obj);
items[1] = [Obj.data[0], Obj.date[0]];
items[2] = [Obj.data[1], Obj.date[1]];
let csvContent = '';
items.forEach((rowArray) => {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
console.log(csvContent)
}
downloadFile();
Below is an example of how to download HTML table to CSV. And as you are working with angular you can create a table from your data using '*ngFor'.
function toCsv() {
const csv = [];
const rows = document.getElementById('table').querySelectorAll("tr");
for (let i = 0; i < rows.length; i++) {
let row = [];
const cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++) {
row.push(cols[j].innerText);
}
csv.push(row.join(","));
}
console.log(csv.join('\r\n'));
}
table {
display: none;
}
<table id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Geronimo</td>
<td>26</td>
<td>France</td>
</tr>
<tr>
<td>Natalia</td>
<td>19</td>
<td>Spain</td>
</tr>
<tr>
<td>Silvia</td>
<td>32</td>
<td>Russia</td>
</tr>
</table>
<button onclick="toCsv()">Export HTML table to CSV file</button>
Use Filesaver to downlad these CSV string to file.
Hope this helps :)
Upvotes: 1
Reputation: 4443
You can try this:
const data = [
[12, "2018-10-10"],
[123, "city2", "more info"]
];
let csvContent = "data:text/csv;charset=utf-8,";
data.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
Upvotes: 0