I am writing an Excel sheet using interop. In the sheet I need to put a set of sentences in to a cell. The text should be in a line break manner. How can I achieve this?
Thanks in advance.
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))
来源:https://stackoverflow.com/questions/8613850/c-sharp-excel-interop-put-a-line-break-in-the-text-of-a-cell-in-a-excel