基于 EasyExcel 实现 Excel 的读写操作,可用于实现最常见的 Excel 导入导出等功能。
Excel 导入导出功能涉及前后端协作,后端处理数据查询、文件生成和解析,前端提供用户交互和文件下载/上传界面。以下是全流程解析,分为导出流程和导入流程。
代码:
@GetMapping("/export")
@Operation(summary = "岗位管理")
@PreAuthorize("@ss.hasPermission('system:post:export')")
@ApiAccessLog(operateType = EXPORT)
public void export(HttpServletResponse response, @Validated PostPageReqVO reqVO) throws IOException {
// ① 查询数据
reqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
List list = postService.getPostPage(reqVO).getList();
// ② 导出 Excel
ExcelUtils.write(response, "岗位数据.xls", "岗位列表", PostRespVO.class,
BeanUtils.toBean(list, PostRespVO.class));
}
解析:
代码:
@Schema(description = "管理后台 - 岗位信息 Response VO")
@Data
@ExcelIgnoreUnannotated
public class PostRespVO {
@Schema(description = "岗位序号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
@ExcelProperty("岗位序号")
private Long id;
@Schema(description = "岗位名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "小土豆")
@ExcelProperty("岗位名称")
private String name;
@Schema(description = "岗位编码", requiredMode = Schema.RequiredMode.REQUIRED, example = "yudao")
@ExcelProperty("岗位编码")
private String code;
@Schema(description = "显示顺序不能为空", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
@ExcelProperty("岗位排序")
private Integer sort;
@Schema(description = "状态,参见 CommonStatusEnum 枚举类", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
@ExcelProperty(value = "状态", converter = DictConvert.class)
@DictFormat(DictTypeConstants.COMMON_STATUS)
private Integer status;
@Schema(description = "备注", example = "快乐的备注")
private String remark;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDateTime createTime;
}
解析:
代码:
public static void write(HttpServletResponse response, String filename, String sheetName,
Class head, List data) throws IOException {
EasyExcel.write(response.getOutputStream(), head)
.autoCloseStream(false)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.registerWriteHandler(new SelectSheetWriteHandler(head))
.registerConverter(new LongStringConverter())
.sheet(sheetName).doWrite(data);
response.addHeader("Content-Disposition", "attachment;filename=" + HttpUtils.encodeUtf8(filename));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
}
解析:
代码:
handleExport() {
const queryParams = this.queryParams;
this.$modal.confirm('是否确认导出所有岗位数据项?').then(() => {
this.exportLoading = true;
return exportPost(queryParams);
}).then(response => {
this.$download.excel(response, '岗位数据.xls');
}).finally(() => {
this.exportLoading = false;
});
}
解析:
代码:
@PostMapping("/import")
@Operation(summary = "导入用户")
@Parameters({
@Parameter(name = "file", description = "Excel 文件", required = true),
@Parameter(name = "updateSupport", description = "是否支持更新,默认为 false", example = "true")
})
@PreAuthorize("@ss.hasPermission('system:user:import')")
public CommonResult importExcel(@RequestParam("file") MultipartFile file,
@RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
List list = ExcelUtils.read(file, UserImportExcelVO.class);
return success(userService.importUserList(list, updateSupport));
}
解析:
code:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = false)
public class UserImportExcelVO {
@ExcelProperty("登录名称")
private String username;
@ExcelProperty("用户名称")
private String nickname;
@ExcelProperty("部门编号")
private Long deptId;
@ExcelProperty("用户邮箱")
private String email;
@ExcelProperty("手机号码")
private String mobile;
@ExcelProperty(value = "用户性别", converter = DictConvert.class)
@DictFormat(DictTypeConstants.USER_SEX)
private Integer sex;
@ExcelProperty(value = "账号状态", converter = DictConvert.class)
@DictFormat(DictTypeConstants.COMMON_STATUS)
private Integer status;
}
解析:
Code:
public static List read(MultipartFile file, Class head) throws IOException {
return EasyExcel.read(file.getInputStream(), head, null)
.autoCloseStream(false)
.doReadAllSync();
}
解析:
Code:
将文件拖到此处,或点击上传
是否更新已经存在的用户数据
仅允许导入xls、xlsx格式文件。
下载模板
解析:
导出流程:
导入流程:
EasyExcel Converter 接口:
DictConvert 作用:
以下是 DictConvert 的代码和逐行解析:
@Slf4j
public class DictConvert implements Converter
解析:
作用:
以下是文档中提到的 EasyExcel 注解,结合代码和上下文说明其作用,并提供实例。
@ExcelProperty("岗位名称") private String name;
@ColumnWidth(18) @ExcelProperty("岗位编码") private String code;
@ContentFontStyle(fontName = "Arial", fontHeightInPoints = 12, bold = true) @ExcelProperty("岗位名称") private String name;
@ContentLoopMerge(eachRow = 2) @ExcelProperty("部门") private String dept;
@ContentRowHeight(20) @ExcelProperty("备注") private String remark;
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER, fillBackgroundColor = IndexedColors.YELLOW) @ExcelProperty("状态") private Integer status;
@HeadFontStyle(fontName = "Calibri", bold = true) @ExcelProperty("岗位名称") private String name;
@HeadRowHeight(25) @ExcelProperty("岗位编码") private String code;
@HeadStyle(fillForegroundColor = IndexedColors.BLUE) @ExcelProperty("状态") private Integer status;
@ExcelIgnore private String internalCode;
@ExcelIgnoreUnannotated public class PostRespVO { @ExcelProperty("岗位名称") private String name; private String remark; // 未标注 }