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:
- The header text,
# 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 :)
