C# Excel interop, put a line break in the text of a cell in a Excel

女生的网名这么多〃 提交于 2019-11-28 13:35:39

It was done by either entering "\r\n" or Environment.NewLine. And also must remember to make WrapText property true in order to visible the line brakes.

you can add style to cells programically as bellow

worksheet.Cells.Style.WrapText = true;

New line within an Excel cell is the LF character, which is "\n" in C#. And do not forget to set the WrapText property of the cell to TRUE.

In VB, or VBA, I used to use vbCrLf (case sensitive) to separate sentences to separate lines in an Excel's Cell like the following:

Dim myString As String
myString = "First sentence" & vbCrLf & "Second sentence"
ActiveCell.ForumulaR1C1 = myString

In C#, I am rather confident that the C# equivalent of VB's vbCrLf is "\r\n", hence:

myString = "First sentence\r\n" + "Second sentence"

New line within an Excel cell is the LF character, which is "\n" in C#.

I have encountered this problem but difference is I do not have access to the worksheet in code as I only pass it to memorystream then create file as .csv type.

foreach (var s in propertyValues)
                streamWriter.WriteLine(s);

            streamWriter.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);

the I use it from here.

 subjExportData.FileStream = stream;
            subjExportData.FileName = string.Format("SubjectExport_{0}.csv", DateTime.Now.ToString("ddMMyyyy_HHmm"));

So the suggestion here to set text or cell wrap is not an option. Got it working using the above answer plus put a double quote before and after the text/string. The replace is to handle when the sentence has a double quote too inside it. So this solution handles, new line, comma and double quotes inside a sentence or paragraph.

if (value.ToString().Contains("\n"))
                                {
                                    value = value.ToString().Replace("\n", "\r\n");
                                    sb.Append('"'+ value.ToString().Replace(@"""", @"""""") + '"'+ ",");
                                }

the answer of this issue is to add a "quot" in front and at the end of the string you want to display in your excel cell. In C# it would be something like (Convert.ToChar(34) + stringToExport + Convert.ToChar(34))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!