开发者

How to write data on multiple lines BUT within the same cell of csv?

开发者 https://www.devze.com 2023-03-15 22:21 出处:网络
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.

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 ach开发者_运维百科ieve 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?


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"


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.


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


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


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());


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

0

精彩评论

暂无评论...
验证码 换一张
取 消