导入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>4.0.1</version>
</dependency>
1、alibaba.excel.EasyExcel导出工具类
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;public class ExcelUtil {/*** 导出excel** @param response 响应* @param list 数据集* @param clazz 类名* @param fileName 文件名* @return*/public static<T> void exportExcel(HttpServletResponse response, List<T> list, Class<T> clazz, String fileName) {try {response.setCharacterEncoding("utf-8");response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");EasyExcel.write(response.getOutputStream(), clazz).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自适应表格格式.sheet("sheet1").doWrite(list);}catch (Exception e){throw new RuntimeException(e.getMessage());}}
}
2、controller层
@GetMapping("/export")public void exportExcel(HttpServletResponse response,OpreationLogEntity opreationLogEntity){List<OpreationLogEntity> oprLogList = opreationLogService.findOprLogList(opreationLogEntity);ExcelUtil.exportExcel(response,oprLogList,OpreationLogEntity.class,"系统日志");}
3、测试:浏览器地址栏输入url即可导出成功