Search code examples
c#epplus

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


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...


Solution

  • 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.)