Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get LineBreaks in a single Cell in EPPlus with RichText

Tags:

c#

epplus

I use the following Code:

using (var package = new ExcelPackage()) {    
    var worksheet = package.Workbook.Worksheets.Add("Test");    
    var cell = worksheet.Cells[1, 1];

    var r1 = cell.RichText.Add("TextLine1" + "\r\n");
    r1.Bold = true;
    var r2 = cell.RichText.Add("TextLine2" + "\r\n");
    r2.Bold = false;

    package.SaveAs(...);
}

But in the Excel file the newLines are gone...

I tried also with "\n" and "\r" but nothing was working...

like image 273
Markus Avatar asked Mar 14 '18 17:03

Markus


Video Answer


2 Answers

Finally I found the solution. Here is a working sample:

    using (var package = new ExcelPackage(fileInfo)) {    
         var worksheet = package.Workbook.Worksheets.Add("Test");    
         var cell = worksheet.Cells[1, 1];
         cell.Style.WrapText = true;
         cell.Style.VerticalAlignment = ExcelVerticalAlignment.Top;

         var r1 = cell.RichText.Add("TextLine1" + "\r\n");
         r1.Bold = true;
         var r2 = cell.RichText.Add("TextLine2" + "\r\n");
         r2.Bold = false;

         package.Save();
     }

But I think I found a bug in the Lib: This Code is NOT working:

    using (var package = new ExcelPackage(fileInfo)) {    
         var worksheet = package.Workbook.Worksheets.Add("Test");    
         var cell = worksheet.Cells[1, 1];
         cell.Style.WrapText = true;
         cell.Style.VerticalAlignment = ExcelVerticalAlignment.Top;

         var r1 = cell.RichText.Add("TextLine1" + "\r\n");
         r1.Bold = true;
         var r2 = cell.RichText.Add("TextLine2" + "\r\n");
         r2.Bold = false;

         cell = worksheet.Cells[1, 1];
         var r4 = cell.RichText.Add("TextLine3" + "\r\n");
         r4.Bold = true;

         package.Save();
     }

When I get the same range again and add new RichText Tokens, the old LineBreaks are deleted... (They are actually converted to "\n" and this is not working in Excel.)

like image 98
Markus Avatar answered Oct 17 '22 21:10

Markus


The Encoding of new line in excel cell is 10. I think you have to do someihing like thise:

var r1 = cell.RichText.Add("TextLine1" + ((char)10).ToString());
like image 33
Tricinty Avatar answered Oct 17 '22 22:10

Tricinty