How to set a line break inside a cell?

8 Dec 20232 minutes to read

In order to set a line break inside a cell, you have to enable Text Wrapping for the cell, and then break the text. The following code snippet illustrates this.

using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Excel2013;
  IWorkbook workbook = application.Workbooks.Create(1);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Save the line break inside the cell
  worksheet.Range["A1"].CellStyle.WrapText = true;
  worksheet.Range["A1"].Text = String.Format("Hello\nworld");

  FileStream stream = new FileStream("LineBreak.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
  workbook.SaveAs(stream);
  workbook.Close();
  excelEngine.Dispose();
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
  IApplication application = excelEngine.Excel;
  application.DefaultVersion = ExcelVersion.Excel2013;
  IWorkbook workbook = application.Workbooks.Create(1);
  IWorksheet worksheet = workbook.Worksheets[0];

  //Save the line break inside the cell
  worksheet.Range["A1"].CellStyle.WrapText = true;
  worksheet.Range["A1"].Text = String.Format("Hello\nworld");
  workbook.SaveAs("LineBreak.xlsx");
}
Using excelEngine As ExcelEngine = New ExcelEngine()
  Dim application As IApplication = excelEngine.Excel
  application.DefaultVersion = ExcelVersion.Excel2013
  Dim workbook As IWorkbook = application.Workbooks.Create(1)
  Dim worksheet As IWorksheet = workbook.Worksheets(0)

  'Save the line break inside the cell
  worksheet.Range("A1").CellStyle.WrapText = True
  worksheet.Range("A1").Text = String.Format("Hello" & vbLf & "world")
  workbook.SaveAs("LineBreak.xlsx")
End Using

See Also