Java开发,用apache的 POI 写excel文件,实现自动换行

今天用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";

原创文章 161 获赞 19 访问量 6万+

猜你喜欢

转载自blog.csdn.net/hefrankeleyn/article/details/103787196
今日推荐