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

java POI实现Excel单元格内容换行_第1张图片

pom.xml

	  <dependency>
   			<groupId>org.apache.poigroupId>
   			<artifactId>poiartifactId>
   			<version>3.15version>
  		dependency>
  		<dependency>
   			<groupId>org.apache.poigroupId>
   			<artifactId>poi-ooxmlartifactId>
   			<version>3.15version>
  		dependency>
  		
  		
  		<dependency>
   			<groupId>commons-iogroupId>
   			<artifactId>commons-ioartifactId>
   			<version>2.5version>
  		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());

	}
}

结果:

java POI实现Excel单元格内容换行_第2张图片

你可能感兴趣的:(java,javase)