如何将换行符作为单元格的数据插入?

问题描述 投票:2回答:2

我使用Apache POI 3.16创建一个Excel文件。我想将特定单元格内的数据设置为有一个换行符:

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

当我打开文件时,单元格值没有换行!那么如何创建换行?

spring spring-mvc apache-poi
2个回答
7
投票

试试这个: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);

3
投票

它已经有换行符,但是单元格没有显示它。您需要设置一个将包装文本属性设置为单元格的单元格样式。

例:

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

 }
}
© www.soinside.com 2019 - 2024. All rights reserved.