0

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:

  1. 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.

enter image description here

  1. 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. enter image description here

Any help for the same is appreciated. Thanks in advance :)

8
  • Try quoting it. Commented Jul 27, 2020 at 14:53
  • @DaveNewton I tried. But no use. Can you help with my code modification? Commented Jul 27, 2020 at 15:36
  • Just add quotes to all the headers. Commented Jul 27, 2020 at 15:55
  • @DaveNewton The quotes are already there Commented Jul 27, 2020 at 17:09
  • I don’t see any code that adds quotes to the string. I could be missing it (on mobile); can you indicate which line is adding quotes to the output? Commented Jul 27, 2020 at 17:20

1 Answer 1

4
+50

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
Sign up to request clarification or add additional context in comments.

2 Comments

As I thought your csv variable does not have the quote marks around the items its just a string ` # Some random long sheet title, # User Id,37467yteyuw8473872938100j # Created on,Wed Jul 29 2020 00:16:41 GMT-0400 (Eastern Daylight Time) Count,Coeff 55,56 55,56 55,56`
Thanks for the thorough explanation :) I will test it out and let you know if any issue ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.