溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行

發(fā)布時(shí)間:2021-07-29 13:39:26 來(lái)源:億速云 閱讀:1177 作者:chen 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要講解了“java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行”吧!

java POI Excel單元格內(nèi)容換行

java POI怎么實(shí)現(xiàn)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)建一個(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é)果:

java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行

poi單元格寫(xiě)值強(qiáng)制換行

String str="強(qiáng)制\r\n換行"

在字符串中間加上\r\n就行了~

感謝各位的閱讀,以上就是“java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)java POI怎么實(shí)現(xiàn)Excel單元格內(nèi)容換行這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI