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

phe*_*mix 4 spring spring-mvc apache-poi

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

rowConsommationEtRealisation.createCell(0).setCellValue("Consommation (crédits)\r\nRéalisation (produits)");
Run Code Online (Sandbox Code Playgroud)

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

Had*_*i J 12

试试这个:这里

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);
Run Code Online (Sandbox Code Playgroud)


Axe*_*ter 5

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

例子:

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

 }
}
Run Code Online (Sandbox Code Playgroud)