34

I use Apache POI 3.16 to create an Excel file. I want to set the data inside a particular cell to have a linebreak :

rowConsommationEtRealisation.createCell(0).setCellValue("Consommation (crédits)\r\nRéalisation (produits)");

When I open the file then the cell value does not have linebreak ! So how to create linebreak ?

robd
  • 9,646
  • 5
  • 40
  • 59
pheromix
  • 18,213
  • 29
  • 88
  • 158

2 Answers2

62

Try this: here

Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");

//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
Hadi J
  • 16,989
  • 4
  • 36
  • 62
10

It has the line break already but the cell does not show it. You need setting a cell style having wrap text property set to the cell.

Example:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;


class ExcelLineBreakWrapText {

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();

  CellStyle wrapStyle = workbook.createCellStyle();
  wrapStyle.setWrapText(true);

  Row row = sheet.createRow(0);

  Cell cell = row.createCell(0); 
  cell.setCellStyle(wrapStyle);
  cell.setCellValue("Consommation (crédits)\r\nRéalisation (produits)");

  sheet.autoSizeColumn(0);

  workbook.write(new FileOutputStream("ExcelLineBreakWrapText.xlsx"));
  workbook.close();

 }
}
Axel Richter
  • 56,077
  • 6
  • 60
  • 87