Java >> Java tutorial >  >> Tag >> break

Hvordan indsætter man et linjeskift som data for en celle?

Prøv dette:her

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

Den har allerede linjeskiftet, men cellen viser det ikke. Du skal indstille en cellestil med egenskaben ombryd tekst til cellen.

Eksempel:

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

 }
}

Java tag