java POI实现Excel单元格内容换行

本文介绍了如何使用Java的POI库处理Excel文件时,实现单元格内容的换行操作。通过调整pom.xml依赖并编写核心代码,可以成功在Excel单元格中显示多行文本。

在这里插入图片描述

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(); // 换行的关键,自定义单元格内容换行规则
		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());

	}
}

结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值