EasyPoi实现Excel导入导出️
1.导入依赖
<dependency>
<groupId>cn.afterturngroupId>
<artifactId>easypoi-spring-boot-starterartifactId>
<version>4.4.0version>
dependency>
2.在实体类的字段添加注解
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("mu_tag")
@ApiModel(value = "Tag对象", description = "标签")
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "名称")
@Excel(name = "名称")
private String name;
@ApiModelProperty(value = "创建人")
@TableField(fill = FieldFill.INSERT)
@Excel(name = "创建人")
private String createdBy;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
@Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
private Date createdTime;
@ApiModelProperty(value = "更新人")
@TableField(fill = FieldFill.INSERT_UPDATE)
@Excel(name = "更新人")
private String updatedBy;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
private Date updatedTime;
}
3.封装工具类
public class ExcelUtil {
static public <T> void export(String title, String sheetName, Class<T> beanClass, List<T> list, HttpServletResponse response) {
ExportParams params = new ExportParams(title, sheetName, ExcelType.HSSF);
Workbook workbook = ExcelExportUtil.exportExcel(params, beanClass, list);
ServletOutputStream out = null;
try {
response.setHeader("content-type", "application/octet-stream");
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode(title + ".xls", "UTF-8"));
out = response.getOutputStream();
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static public <T> ResponseResult importExcel(MultipartFile file, Class<T> beanClass, Object service) {
try {
List<T> list = getListFromExcel(file, beanClass);
String methodName = "saveBatch";
Object success = ReflectUtil.invokeMethodByName(service, methodName, new List[]{list});
if (BooleanUtil.isTrue(Convert.toBool(success))) {
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
} catch (Exception e) {
e.printStackTrace();
}
return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
}
static public <T> List<T> getListFromExcel(MultipartFile file, Class<T> beanClass) throws Exception {
ImportParams params = new ImportParams();
params.setTitleRows(1);
return ExcelImportUtil.importExcel(file.getInputStream(), beanClass, params);
}
}