java POI 如何實(shí)現(xiàn)Excel單元格內(nèi)容換行
更新時間:2021年07月29日 10:38:17 作者:congcongxianshen
這篇文章主要介紹了java POI 如何實(shí)現(xiàn)Excel單元格內(nèi)容換行的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
java POI Excel單元格內(nèi)容換行

pom.xml
<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>
核心代碼
@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(); // 換行的關(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)建一個單元格
// 如下也是可以的
//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é)果:

poi單元格寫值強(qiáng)制換行
String str="強(qiáng)制\r\n換行"
在字符串中間加上\r\n就行了~
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
java調(diào)用通義千問API的詳細(xì)完整步驟
通義千問是阿里云自主研發(fā)的大語言模型,能夠在用戶自然語言輸入的基礎(chǔ)上,通過自然語言理解和語義分析,理解用戶意圖,在不同領(lǐng)域、任務(wù)內(nèi)為用戶提供服務(wù)和幫助,下面這篇文章主要給大家介紹了關(guān)于java調(diào)用通義千問API的詳細(xì)完整步驟,需要的朋友可以參考下2024-02-02
教你如何精準(zhǔn)統(tǒng)計出你的接口"QPS"
今天小編就為大家分享一篇關(guān)于QPS的精準(zhǔn)計算方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2021-08-08
java基本教程之Thread中start()和run()的區(qū)別 java多線程教程
這篇文章主要介紹了Thread中start()和run()的區(qū)別,Thread類包含start()和run()方法,它們的區(qū)別是什么?下面將對此作出解答2014-01-01

