今天用Java开发写excel的功能,需要用到强制换行。
思路如下:
String localFilePath="D:\\pro_exchangedir\\2019-12-31-换行测试.xlsx";
Workbook wb = new XSSFWorkbook();
CellStyle cellStyle = wb.createCellStyle();
String str = "world"+"\r\n"+"pass";
// 设置强制换行
cellStyle.setWrapText(true);
....
cell.setCellValue(wb.getCreationHelper().createRichTextString(str));
try (OutputStream fileOut = new FileOutputStream(file)) {
wb.write(fileOut);
} catch (IOException e) {
throw new RuntimeException(e);
}
wb.close();
遇到一个奇怪的问题:如果将 换行的字符串写成下面的样子,则不会换行:
String str = "world\r\npass";
必须写成下面的样子,才会换行:
String str = "world"+"\r\n"+"pass";