使用easypoi导出excel
//依赖jar包 springboot方式
<!-- easypoi --> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.0.0</version> </dependency>
//js
function exportExcel() { var url = "/sys/user/export"; var args = { username:$('#searchName').val() }; var params = Object.keys(args).map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); }).join("&"); window.location.href = url+"?"+params; }
//Vo
public class UserVO implements Serializable { @Excel(name = "登录名", width = 20) private String username; @Excel(name = "姓名", width = 20) private String realname; @Excel(name = "性别", replace = {"未知的性别_0","男性_1", "女性_2","未说明的性别_9"},width = 20) private int sex; @Excel(name = "电话", width = 20) private String moblie; @Excel(name = "邮箱", width = 20) private String email; @Excel(name = "状态", replace = {"禁用_0","启用_1"}, width = 20) private int state; @Excel(name = "创建时间", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd",width = 20) private Date createdat; //以下省略get set方法 }
//java
/** * 导出 */ @GetMapping("/export") public void export(@RequestParam Map<String, Object> params,HttpServletResponse response) { List<UserVO> userList = userService.export(params); ExportParams exportParams = new ExportParams("用户表", "user"); exportParams.setType(ExcelType.XSSF); Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams,UserVO.class, userList); ExcelExportUtil.closeExportBigExcel(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter); String fileName = "user"+dateTime+".xlsx"; if (workbook != null) { downLoadExcel(fileName, response, workbook); } } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }