1

I create a CSV from javascript array of objects using the json2csv module. This is what I do

const list = [{name: "xyz", city: "abc"},{name: "foo", city: "def"}];

const json2csvParser = new Parser({fields: headers});
const csv = json2csvParser.parse(list);

Now, for the CSV created by converting array of objects, I need to prepend a row (add a new row at the top) and fill only the first cell. It will look similar to the following

enter image description here

Here is what I tried:

const newLine = `"First Line
   Second Line"`;

const updatedCSV = newLine + csv;

Now, if I open this CSV using google spreadsheet, it shows the prepended value in cell, with line breaks. But if I open the same in Microsoft Excel, it shows as follows:

enter image description here

There are multiple rows created and " are also visible. How can I make it seamless, so that it opens the same everywhere, which always shows one row with multiple line breaks. I need to be able to add the line breaks within a cell.

I referred to

but it did not help.

When I try to open the file using a text editor, this is how it looks like:

enter image description here

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • What does the actual csv file look like (open in a text editor like Notepad++). For Excel to honor the linebreak, you need to have double quotes `"` around the string. To display it, be sure to enable wordwrap for the cell(s). – Ron Rosenfeld Dec 18 '21 at 13:31
  • @RonRosenfeld I have updated the screenshot, of how it looks like when opened with a text editor. As you can see, there are `"` around `How to use ... Column B` – Suhail Gupta Dec 18 '21 at 13:35
  • @RonRosenfeld It will be great, if you could provide a small example on how would you do it. I have been struggling with it for sometime now. – Suhail Gupta Dec 18 '21 at 13:39
  • Your problem is at the very beginning. The quote marks have to be around the **entire** entry and start either at the very beginning of the line, or **immediately** after a comma if not in the first cell. Your opening quote mark, in the first line, is in the third position. I suggest you delete the `| ` (pipe) to obtain your desired result. – Ron Rosenfeld Dec 19 '21 at 00:45
  • @RonRosenfeld Thanks that solved the issue. I think, this will make a very good answer. The response stream was adding 2 spaces and this went unnoticed. – Suhail Gupta Dec 20 '21 at 07:44

0 Answers0