how to put a line break in excel cell in NPOI in C#?

Rahul Kiwitech
Rahul K...
292 Points
26 Posts

I am using NPOI packet to export report in excel format. I want to split content in new line in a cell. I am trying following code:

 IWorkbook wb = new HSSFWorkbook();
ICellStyle style = wb.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;

ISheet sheet = wb.CreateSheet("Orders");
IRow row = sheet.CreateRow(0);

AddStyledCell(row, 0, hstyle).SetCellValue("#");
AddStyledCell(row, 1, hstyle).SetCellValue("NAME");
AddStyledCell(row, 2, hstyle).SetCellValue("ADDRESS");

row = sheet.CreateRow(i++);
AddStyledCell(row, 0, style).SetCellValue("1");
AddStyledCell(row, 1, style).SetCellValue("name");
AddStyledCell(row, 2, style).SetCellValue("line1\nline2");

But I unable to break new line. I want 
line1
line2
But it print as:
line1\nline2

 

Views: 20523
Total Answered: 3
Total Marked As Answer: 1
Posted On: 23-Feb-2017 02:09

Share:   fb twitter linkedin
Answers
Smith
Smith
2890 Points
78 Posts
         

Try following:

 IWorkbook wb = new HSSFWorkbook();
ICellStyle style = wb.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.WrapText = true;

ISheet sheet = wb.CreateSheet("Orders");
IRow row = sheet.CreateRow(0);

AddStyledCell(row, 0, hstyle).SetCellValue("#");
AddStyledCell(row, 1, hstyle).SetCellValue("NAME");
AddStyledCell(row, 2, hstyle).SetCellValue("ADDRESS");

row = sheet.CreateRow(i++);
AddStyledCell(row, 0, style).SetCellValue("1");
AddStyledCell(row, 1, style).SetCellValue("name");
AddStyledCell(row, 2, style).SetCellValue("line1" + Environment.NewLine + "line2");

In this WrapText = true; is reqired.

Posted On: 24-Feb-2017 02:05
sam
sam
378 Points
48 Posts
         

Yes, Finally I found the solution. Just remember two things

set style:

style.WrapText = true;

and second

AddStyledCell(row, 2, style).SetCellValue("line1" + Environment.NewLine + "line2");

Thanks...

Posted On: 08-May-2017 08:51
beginer
beginer
1576 Points
53 Posts
         

Also, we can use 'HSSFRichTextString' as:

using NPOI.HSSF.UserModel;
HSSFRichTextString richString = new HSSFRichTextString("line1\nline2");
AddStyledCell(row, 2, style).SetCellValue(richString);
Posted On: 03-Nov-2017 04:22
 Log In to Chat