网上很多博客操作Excel换行的都是Office2007之前的格式,一直没找到支持扩展名为.xlsx的换行方式,被折腾到要死,无奈之下只能去官网看看,发现了同时支持.xlsx和.xls两种扩展的。现在列出如下:
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
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);
//increase row height to accomodate two lines of text
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
//adjust column width to fit the content
sheet.autoSizeColumn((short)2);
FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
官网链接如下:
POI NewLinesInCells