C # excel interop, put line break in cell text in Excel

I am writing an Excel worksheet using interop. In the sheet I need to put a set of sentences in a cell. The text should be in line break mode. How can I achieve this?

Thanks in advance.

+6
source share
7 answers

This was done by entering "\ r \ n" or "Environment.NewLine". Also, keep in mind that the WrapText property is true for visible linear brakes.

+6
source

you can add style to the cells programmatically as below

worksheet .Cells.Style.WrapText = true;

+3
source

The new line in the Excel cell is the LF character, which is "\n" in C #.

+1
source

The new line in the Excel cell is the LF character, which is "\ n" in C #. And don't forget to set the WrapText property of the cell to TRUE.

+1
source

In VB or VBA, I used vbCrLf (case sensitive) to split sentences to split rows in an Excel cell as follows:

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

In C #, I am sure that the C # equivalent for VB vbCrLf is "\r\n" , therefore:

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

I ran into this problem, but the difference is that I do not have access to the sheet in the code, because I only pass it to memystream and then create the file as a CSV type.

 foreach (var s in propertyValues) streamWriter.WriteLine(s); streamWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); 

I use it here.

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

Therefore, the proposal to install text wrapping or cells is not an option. Having received it using the above answer, add a double quote before and after the text / line. Replacements must be processed when the sentence contains a double quote. Thus, this solution processes a new line, a comma, and double quotation marks inside a sentence or paragraph.

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

The answer to this problem is to add "quot" in front and at the end of the line that you want to display in your excel cell. In C #, it will be something like (Convert.ToChar (34) + stringToExport + Convert.ToChar (34))

-2
source

Source: https://habr.com/ru/post/904373/


All Articles