java POI 如何實現Excel單元格內容換行
<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(); // 換行的關鍵,自定義單元格內容換行規則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());}}
結果:
String str='強制rn換行'
在字符串中間加上rn就行了~
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: