yoni349
yoni349

Reputation: 227

How to write text with line space to a CSV file?

I'm getting product descriptions in an object with strings. I'd like to write the data to a CSV file so I can do some data analysis.

I need the data to be visually good looking so I can easily read it. The thing is, all I get so far is a bunch of tight hard to read strings.

If you edit from excel you'll use Alt+Enter, which will create some space in the same row. How do I write to the file with some line spaces, that doesn't create a new row in excel?

I found that:

  1. \n is copied as test
  2. \r\n is starting a new row instead only spacing the row

For example:

fs.appendFile(`./data/testCSV.csv`,  encodeURIComponent(element.name +'\r\n'+ element.description + '\r\n'+ element.short_description), function (err) {
 if (err) throw err;
});

Will give it in 3 separated rows

Here is an example of how I'd like it to look like:

CSV example

Also tried to find an NPM parser, but all of them create new lines as well.

Upvotes: 0

Views: 2893

Answers (2)

yoni349
yoni349

Reputation: 227

Thanks to Danny_ds.

This variable version works well:

 `"${x} \n ${y} \n\n ${z}"` 

Upvotes: 0

Danny_ds
Danny_ds

Reputation: 11406

To have multiline fields in a csv you need to enclose the field with quotes:

123,"multi 
line 
text",456

Quotes inside the fields have to be escaped with another quote:

123,"Samsung 
24"" 
monitor",456

Not sure if Excel will hanlde this right though.

Upvotes: 1

Related Questions