java POI Excel单元格内容换行
pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
< dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi</ artifactId > < version >3.15</ version > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-ooxml</ artifactId > < version >3.15</ version > </ dependency > < dependency > < groupId >commons-io</ groupId > < artifactId >commons-io</ artifactId > < version >2.5</ version > </ dependency > |
核心代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
@RestController public class MyController { @RequestMapping ( "/ip/v5" ) public void getExcel(HttpServletResponse response) throws IOException { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add( "this is 单元格第1行" ); arrayList.add( "this is 单元格第2行" ); arrayList.add( "this is 单元格第3行" ); arrayList.add( "this is 单元格第4行" ); XSSFWorkbook workBook = new XSSFWorkbook(); XSSFSheet sheet = workBook.createSheet(); workBook.setSheetName( 0 , "ip-v4表" ); XSSFCellStyle cs = workBook.createCellStyle(); // 换行的关键,自定义单元格内容换行规则 cs.setWrapText( true ); String fileName = "china-ip-v4" + ".xls" ; // 设置要导出的文件的名字 String[] headers = { "掩码" }; XSSFRow titleRow = sheet.createRow( 0 ); // 在excel表中添加表头 for ( int i = 0 ; i < headers.length; i++) { titleRow.createCell(i).setCellValue(headers[i]); } String content = String.join( "\n" , arrayList); int rowNum = 1 ; XSSFRow row1 = sheet.createRow(rowNum); // 创建一行 XSSFCell cell = row1.createCell( 0 ); // 创建一个单元格 // 如下也是可以的 //cell.setCellValue("this is 单元格第1行 \n this is单元格第2行 \n this is 单元格第3行 \n this is 单元格第4行"); cell.setCellValue(content); cell.setCellStyle(cs); response.setContentType( "application/octet-stream" ); response.setHeader( "Content-disposition" , "attachment;filename=" + fileName); response.flushBuffer(); workBook.write(response.getOutputStream()); } } |
结果:
poi单元格写值强制换行
1
|
String str= "强制\r\n换行" |
在字符串中间加上\r\n就行了~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/congcongxianshen/article/details/100746858