1.添加依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.写一个测试代码
package com.lyr.demoTest.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/excel")
public class ExcelController {
@RequestMapping("/tt")
public void hutoolExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
TestBean bean1 = new TestBean();
bean1.setName("张三");
bean1.setAge(22);
bean1.setPass(true);
bean1.setScore(66.30);
bean1.setExamDate(DateUtil.date());
TestBean bean2 = new TestBean();
bean2.setName("李四");
bean2.setAge(28);
bean2.setPass(false);
bean2.setScore(38.50);
bean2.setExamDate(DateUtil.date());
List<TestBean> rows = CollUtil.newArrayList(bean1, bean2);
ExcelWriter writer = ExcelUtil.getWriter(true);
writer.addHeaderAlias("name","姓名");
writer.addHeaderAlias("age","年龄");
writer.write(rows, true);
String fileName = "我是谁";
ExcelXlsxHandler(request, response, writer, fileName);
}
public void ExcelXlsxHandler(HttpServletRequest request, HttpServletResponse response, ExcelWriter writer, String fileName) throws IOException {
final String userAgent = request.getHeader("user-agent");
if (StringUtils.isNotBlank(userAgent)&&(userAgent.indexOf("Firefox") >= 0
|| userAgent.indexOf("Chrome") >= 0 || userAgent.indexOf("Safari") >= 0)){
fileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF8");
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
final ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
writer.close();
IoUtil.close(out);
}
}
3.拿去用就行,别问我问什么,哈哈哈