Reputation: 305
Following with the help of various solutions around, I have a javascript CSV function that converts the JSON data into CSV format.
This is how the code goes:
function convertToCSV(headers, objArray) {
var header_line = "";
for (const [key, value] of Object.entries(headers)) {
header_line += [key, value] + "\n";
}
var array = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
var str = "";
for (var i = 0; i < array.length; i++) {
var line = "";
for (var index in array[i]) {
if (line !== "") line += ",";
line += array[i][index];
}
str += line + "\r\n";
}
var csv = header_line + "\n" + str;
return csv;
}
function exportCSVFile(headers, columns, items, fileTitle) {
if (columns) {
items.unshift(columns);
}
var jsonObject = JSON.stringify(items);
var csv = convertToCSV(headers, jsonObject);
var exportedFilenmae = fileTitle + ".csv" || "export.csv";
var blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var 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 function generateCSV(dataarray, filename) {
var columns = {
"Count": "Count",
Coeff: "Coeff",
};
var headers = {
"# Some random long sheet title": "",
"# User Id": "37467yteyuw8473872938100j",
"# Created on": new Date() + "\t\t",
};
let json_data= [
{
"Count": "55",
Coeff: "56",
},
{
"Count": "55",
Coeff: "56",
},
{
"Count": "55",
Coeff: "56",
},
];
var formatItems = [];
json_data.forEach((item) => {
formatItems.push({
"Count": item["Count"],
Coeff: item["Coeff"]
});
});
var fileTitle = "my_data";
exportCSVFile(headers, columns, itemsFormatted, fileTitle);
}
The functions work completely fine. The problematic cases stuck are:
# Created On
, is getting hidden as the file is downloaded and then opened. On downloading the file, this column needs to be manually dragged so that it's visible completely.If a comma (,) is included in the title key like:
var headers = {
"# Some random long, sheet title": "",
"# User Id": "37467yteyuw8473872938100j",
"# Created on": new Date() + "\t\t",
};
It breaks the title into 2 cols even after is a single string.
Any help for the same is appreciated. Thanks in advance :)
Upvotes: 0
Views: 1910
Reputation: 118
Although you declare the header_line variable (string) with double quotes it is actually just a string. For csv to ignore a coma it must have double quotes around it (within the larger string).
If you console.log() the csv as its generated you should see it currently is something like....
...., # User Id:, 37467yteyuw8473872938100j,
you could try adding escaped quotes to the line
header_line += [key, value] + "\n";
so it becomes header_line += '\"' + [key, value] +'\"' + "\n";
This might not be exactly correct, but you should be able to see from the console and the raw csv file (open the csv file in text editor). In the csv file it should look like this (I think)
"# User Id:, 37467yteyuw8473872938100j",
Disclaimer: I couldn't get your code to run to test it properly.
Edit: The current csv output
# Some random long sheet title,
# User Id,37467yteyuw8473872938100j <--- the Comma is Separating the Values (CSV)
# Created on,Wed Jul 29 2020 00:16:41 GMT-0400 (Eastern Daylight Time)
Count,Coeff
55,56
55,56
55,56
Upvotes: 4