How to insert a linebreak as the data of a cell?

为君一笑 提交于 2020-01-29 15:48:09

问题


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 ?


回答1:


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);



回答2:


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();

 }
}


来源:https://stackoverflow.com/questions/48040638/how-to-insert-a-linebreak-as-the-data-of-a-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!