1. 依赖导入
<!-- 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. 生成excel
Workbook wb = null;
if (result.size() < 1000) {
wb = new XSSFWorkbook();
} else {
wb = new SXSSFWorkbook();
}
//设置表格的格式--居中
CellStyle cs = wb.createCellStyle();
cs.setAlignment(HorizontalAlignment.CENTER);
//创建工作表
Sheet sheet = wb.createSheet("测试");
//设置列宽,有多少列,写多少列,0,1,2,3,4,5..........
sheet.setColumnWidth(0,20 * 256);
//创建行-表头行
Row row = sheet.createRow(0);
//创建格,有多少格创建多少格,0,1,2,3,4,5..........
Cell cell = row.createCell(0);
cell.setCellValue("tt");
cell.setCellStyle(cs);
//写入数据
for (Info info: result) {
row = sheet.createRow(result.indexOf(info) + 1);
//有多少个创建多少格子,0,1,2,3,4,5..........
row.createCell(0).setCellValue(info.getName()!=null?info.getName():"");
}
//提供下载
response(request, response,wb, "文件名称",date);
3. 返回文件
注意:这个不能用异步请求,不然会报错,前端需要注意下。
private void response(HttpServletRequest request, HttpServletResponse response, Workbook wb, String name, String date) throws IOException {
OutputStream outputStream =null;
try {
//设置Http响应头告诉浏览器下载这个附件
outputStream = response.getOutputStream();
String userAgent = request.getHeader("USER-AGENT");
String fileName11;
String fileName = name + date + ".xlsx";
if(StringUtils.contains(userAgent, "Firefox") || StringUtils.contains(userAgent, "firefox")){
//火狐浏览器
fileName11 = new String(fileName.getBytes(), "ISO8859-1");
}else{
//其他浏览器
fileName11 = URLEncoder.encode(fileName,"UTF-8");
}
String headStr = "attachment; filename="" + fileName11 + """;
response.setContentType("application/0000000000000000000000000000");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", headStr);
wb.write(outputStream);
outputStream.flush();
} catch (Exception ex) {
ex.printStackTrace();
}finally {
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
ex.printStackTrace();
}
}
}
}