一、问题
根据读入类的注解,默认只读取表格A-H列的数据。导入的时候会读取H列之外的数据,有可能导致异常;
@Data @Builder @AllArgsConstructor @NoArgsConstructor @Accessors(chain = false) // 设置 chain = false,避免用户导入有问题 public class ShopImportExcelVO extends RowIndex { /** * 商品名称 */ @ExcelProperty(value = "商品ID") private Long id; /** * 商品名称 */ @ExcelProperty(value = "商品名称(必填)") private String name; /** * 商品分类 */ @ExcelProperty(value = "商品分类名称ID(必填)") private Long systemClassificationId; /** * 标准价格 */ @ExcelProperty(value = "标准价格(必填)") private BigDecimal price; /** * 最低价格 */ @ExcelProperty(value = "最低价格(必填)") private BigDecimal minPrice; /** * 商品状态(0正常 1停用) */ @ExcelIgnore private Integer status; @ExcelIgnore private Integer sort; /** * 服务字段 */ @ExcelProperty(value = "服务字段") private String serviceField; /** * 成本费用标准 */ @ExcelProperty(value = "成本费用标准") private String costField; /** * 补充报考字段 */ @ExcelProperty(value = "补充报考字段") private String examinationField; @ExcelIgnore private BigDecimal accountsPayable; /** * 备注 */ @ExcelProperty(value = "备注") private String remark; }
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellExtra; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.Map; @Slf4j public class ShopExcelListener extends AnalysisEventListener<ShopImportExcelVO> { List<ShopImportExcelVO> res; public ShopExcelListener(List<ShopImportExcelVO> res) { this.res=res; } @Override public void onException(Exception exception, AnalysisContext context) throws Exception { log.error("解析失败,但是继续解析下一行:{}", exception.getMessage()); if (exception instanceof ExcelDataConvertException) { ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception; log.error("第{}行,第{}列解析异常,数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData()); } } @Override public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) { } @Override public void invoke(ShopImportExcelVO data, AnalysisContext context) { ReadRowHolder readRowHolder = context.readRowHolder(); Integer rowIndex = readRowHolder.getRowIndex(); data.setRowIndex(rowIndex+1); res.add(data); } @Override public void extra(CellExtra extra, AnalysisContext context) { } @Override public void doAfterAllAnalysed(AnalysisContext context) { log.info("所有数据解析完成!"); log.info("解析数据:{}", JSON.toJSONString(res)); } }
二、官方文档
只要部分字段去匹配excel(excel写入内容匹配不上等)
easyexcel
默认是全部实体字段都会参与读写,不管你是否加了@ExcelProperty
注解
- 如果您的版本低于2.1.6,建升级到以上版本
- 升级了还有,在类的最上面加入
@ExcelIgnoreUnannotated
注解,加入这个注解后只有加了@ExcelProperty
才会参与读写。
安装文档,增加注解@ExcelIgnoreUnannotated,问题解决。