0

Does anyone please know how can we support new lines (/n) for a csv download javascript function?

This is my function

export function exportToCsv(filename, rows) {
  var processRow = function (row) {
    var finalVal = "";
    for (var j = 0; j < row.length; j++) {
      var innerValue = row[j] === null ? "" : row[j].toString();

      var result = innerValue.replace(/"/g, '""');
      if (result.search(/("|,|\n)/g) >= 0) result = '"' + result + '"';
      if (j > 0) finalVal += ";";
      finalVal += result;
    }
    return finalVal + "\n";
  };

  var csvFile = "";
  for (var i = 0; i < rows.length; i++) {
    csvFile += processRow(rows[i]);
  }

  var blob = new Blob([csvFile], { type: "text/csv;charset=utf-8;" });

  var element = document.createElement("a");
  if (element.download !== undefined) {
    var url = URL.createObjectURL(blob);
    element.setAttribute("href", url);
    element.setAttribute("download", filename);
    element.style.display = "none";
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }
}
   const example = [
      ["name", "position"],
      ["Rick", "Morty"],
      ["fullstack \n developer", `Data \nscientist`],
    ];
    exportToCsv("example", example);

The csv file after download it is showing as:

Download_result

The expected /wished result should be like this

enter image description here

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Amaru
  • 21
  • 2
  • Does this answer your question? [Can you encode CR/LF in into CSV files?](https://stackoverflow.com/questions/566052/can-you-encode-cr-lf-in-into-csv-files) – evolutionxbox Jul 19 '23 at 08:33

1 Answers1

0

My advice is to use PapaParse. Otherwise you need to escape the new-line symbols and optionally quote the values:

function json2csv(rows)
{
  return rows.map(row =>
  {
    return (Array.isArray(row) ? row : Object.values(row)).map(column => JSON.stringify(column)).join(',');
  }).join('\r\n');
}
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26