26

I want to create one csv file using C#.

I have some data which I want to write on multiple lines BUT within the same cell.

For example If I have following three sentences,

Sample sentence 1. This is second sample sentence. and this is third sentence.

I want to write all these three sentences within single cell of csv file but I want three of them on separate line.

My expected output is :

Sample sentence 1.
This is second sample sentence.
and this is third sentence.

Currently I am trying to achieve this by using \n character between two sentences but when I do it this way, all three sentences go on separate row.

Can anyone please tell me how to solve this problem?

Shekhar
  • 11,438
  • 36
  • 130
  • 186

6 Answers6

39

To quote Wikipedia:

Fields with embedded line breaks must be enclosed within double-quote characters.

Like e.g.:

1997,Ford,E350,"Go get one now
they are going fast"
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
0

Always wrap your description in between "\" eg: CsvRow.Add("\"" + ID + " : " + description + "\"");

0

You might be able to change which tokens your application uses to parse rows from the csv file, but according to the definition of the csv file format, lines in the file are used to represent rows in the resulting tabular data.

Jeb
  • 15,939
  • 6
  • 34
  • 37
0
string input = "...";

var r = input.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) // split by dot (have you any better approaches?)
             .Select(s => String.Format("\"{0}.\"", s.Trim())); // escape each with quotes

input = String.Join(Environment.NewLine, r); // break by line break
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0
string filePath = @"d:\pandey.csv";
StringBuilder outString=new StringBuilder();
outString.Append("\""); //double quote 
outString.Append("Line 1, Hi I am line 1 of same cell\n");
outString.Append("Line 2 Hi I am line 2 of same cell\n");
outString.Append("Line 3 Hi I am line 3 of same cell\n");
outString.Append("Line 4 Hi I am line 4 of same cell");
outString.Append("\""); //double quote             
File.WriteAllText(filePath, outString.ToString());
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
-2

CSV stands for "comma seperated values" which is just a description of a text-file. If you want to import into Excel and then only have the sentences in one line you should try:

Environment.NewLine

instread of a simple /n

bastianwegge
  • 2,435
  • 1
  • 24
  • 30