使用注解进行导出步骤:
系统导出 使用 ExcelUtils
1:新建excel 包 、新建Excel 类 (例如 SysUserExcel 类)
2:使用@Excel (注解由easyPoi 提供 相关字段解释参考官方文档,文档地址:http://easypoi.mydoc.io/#text_225967)
3:查询数据 映射 SysUserExcel
4:使用ExcelUtils 导出Excel
excel工具类:ExcelUtils.java
package com.demo.common.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* excel工具类
*
* @author system
*/
public class ExcelUtils {
/**
* Excel导出
*
* @param response response
* @param fileName 文件名
* @param list 数据List
* @param pojoClass 对象Class
*/
public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
Class<?> pojoClass) throws IOException {
if(StringUtils.isBlank(fileName)){
//当前日期
fileName = DateUtil.today();
}else{
fileName = fileName + DateUtil.today();
}
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, list);
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
}
/**
* Excel导出,先sourceList转换成List<targetClass>,再导出
*
* @param response response
* @param fileName 文件名
* @param sourceList 原数据List
* @param targetClass 目标对象Class
*/
public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
Class<?> targetClass) throws Exception {
List targetList = new ArrayList<>(sourceList.size());
for(Object source : sourceList){
Object target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
targetList.add(target);
}
exportExcel(response, fileName, targetList, targetClass);
}
}
引入hutool依赖:
<hutool.version>5.7.22</hutool.version>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
导出时控制层代码demo:
/**
* 导出
* @param params
* @param response
* @throws Exception
*/
@PostMapping("/export")
public void export(@RequestBody DemoDTO params, HttpServletResponse response) throws Exception {
params.setPage(1);
params.setLimit(999999999);
PageData<DemoDTO> page = certRecordService.queryGovPage(params);
List<DemoDTO> list = page.getList();
ExcelUtils.exportExcelToTarget(response, null, list, DemoDTOExcel.class);
}
工具类优先使用Hutool 文档参考地址:https://hutool.cn/docs/index.html#/