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

孤人 提交于 2019-12-29 01:35:10

问题


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.


回答1:


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




回答2:


you can add style to cells programically as bellow

worksheet.Cells.Style.WrapText = true;




回答3:


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.




回答4:


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




回答5:


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"



回答6:


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(@"""", @"""""") + '"'+ ",");
                                }



回答7:


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

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