java POI 如何實(shí)現(xiàn)Excel單元格內(nèi)容換行
<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>核心代碼
@RestControllerpublic 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(); // 換行的關(guān)鍵,自定義單元格內(nèi)容換行規(guī)則cs.setWrapText(true);String fileName = 'china-ip-v4' + '.xls';// 設(shè)置要導(dǎo)出的文件的名字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); // 創(chuàng)建一行XSSFCell cell = row1.createCell(0); // 創(chuàng)建一個(gè)單元格// 如下也是可以的//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());}}
結(jié)果:
String str='強(qiáng)制rn換行'
在字符串中間加上rn就行了~
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章: