I have a javascript function I am using to convert some JSON data to an excel export. For the most part, everything is working just fine.
I noticed however that one of my column names now has a comma in it (intentional) LastName, FirstName.
With my existing code, its causing the header column to be separated and moved over into its own column when I expect it to be a single column header.
/**
* Convert the JSON to a CSV File
* @param {*} JSONData
* @param {*} ReportTitle
* @param {*} ShowLabel
*/
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var csv = CSV;
blob = new Blob([csv], {
type: 'text/csv'
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, ReportTitle);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
}
I believe my error is in the if (ShowLabel) { statement.
Is there a way I can ignore the commas in the header row so that my columns will remain aligned?
Error:
Desired:
Any thoughts on how to ignore the commas in the header row?
-
I mean, not splitting on a delimiter in CSV format is a bit odd. You could set it up to split the string on every other comma if the column is "Last Name, First Name", but you would have to be sure that each cell had the exact same format. A.e. no missing names. And of course, this would be very specific so changing the column name at any time would require a change in code.zfrisch– zfrisch2018年12月03日 15:24:15 +00:00Commented Dec 3, 2018 at 15:24
1 Answer 1
I believe you should add quotes around your labels so the comma inside (the quotes) is not treated as a separator
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += '\"' + index + '\",';
}
In your screenshot, Bob, Jones is correctly assigned to one cell although there's a comma. If you open the CSV file in Notepad for instance you should see Bob, Jones has quotes.