easypoi和hutool Excel工具的使用
ExcelUtil是对easypoi的封装,你们找不到的;万变不离其宗,传入List,解析类是E.class,设置一些参数,比如生成表头,从第几行开始,几行结束等等。
String tempStr = "表名";
try {
ExcelUtil.exportExcel(basicSnapshotExcels, tempStr, tempStr,
BasicSnapshotExcel.class, tempStr+".xls", true, response);
} catch (Exception e) {
log.error("导出异常:",e);
return RestResult.fail(ErrorCode.EXCEL_EXPORT_FAIL);
}
记得实体类属性加了@Excel注解才会将这个字段转为excel表的一列
@Data
public class BasicSnapshotExcel implements Serializable {
@ApiModelProperty("0为规则,1为快照")
@Excel(name = "0规则1快照" ,orderNum = "0",width = 15 )
private Boolean ruleOrSnapshot;
@ApiModelProperty("基础规则快照id")
@Excel(name = "id" ,orderNum = "1",width = 15 )
private String id;
@ApiModelProperty(value = "基础规则编号", position = 1)
@Excel(name = "规则编码" ,orderNum = "2",width = 15 )
private String code;
@ApiModelProperty(value = "报警源类型 1:iot类 2:业务类", position = 2)
@Excel(name = "报警源类型" ,orderNum = "3",width = 15 )
private Integer sourceType;
@ApiModelProperty(value = "创建时间", position = 11)
@Excel(name = "创建时间" ,format = "yyyy-MM-dd HH:mm:ss" ,orderNum = "13",width = 15 )
private LocalDateTime createTime;
}
注意时间字段
用easypoi导出LocalDateTime类型没问题,只是做逆向导入的时候一直报错,一遇到时间类型就报空指针异常,没看错,就是空指针。
由于这个错与时间类型八竿子打不着,调试半天才发现每次一到时间字段就出错,时间字段删掉就好了。
我相信,easypoi肯定是能处理时间字段的,只不过我还没去仔细看文档。就草草投入了hutool.poi.excel的怀抱,轻松解决导入时间问题。
hutool.poi.excel导入
无非也是传入文件流以及解析目标的类。
Map<String, String> associateMap = associate();
ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());
reader.setHeaderAlias(associateMap);
List<BasicSnapshotExcel> read = Lists.newArrayList();
try {
read = reader.read(1, 2, BasicSnapshotExcel.class);
} catch (Exception e) {
log.error("导入异常",e);
return false;
}
associate方法用于关联表的列名和字段名,这里用了反射,不然手动put(“规则编码”,“code”),一百字段put一百次。
// 关联标题和字段
private Map<String,String> associate(){
Field[] fields = BasicSnapshotExcel.class.getDeclaredFields();
Map<String,String> head = Maps.newHashMap();
for (Field f : fields){
Boolean excelExist = f.isAnnotationPresent(Excel.class);
if (excelExist){
Excel excel = f.getAnnotation(Excel.class);
head.put(excel.name(),f.getName());
}
}
return head;
}