EasyPoi 导入Excel获取不到第一列的问题
这里我举个例子(我遇到的问题)
我的Excel模板是这样的
但是测试好多次 扫描不到第一列(产品唯一标识)的数据
获取到的结果
第一列标识的modelId 一直是null
错误的代码
@PostMapping("upload")
@Transactional
public Response upload(CustomerPrice customerPrice,@RequestParam("file") MultipartFile multipartFile) throws Exception {
try {
ImportParams params = new ImportParams();
//标题和表头不能混合起来 用表头 = 2来代替标题 这样会导致第一列读取不到
params.setHeadRows(2);
// params.setTitleRows(1);
List<CustomerPrice> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
CustomerPrice.class, params);
System.out.println(result.toString());
CustomerPrice customerPrice1 = new CustomerPrice();
//第一步 先删除
customerPriceService.deleteByCompany(customerPrice.getMerchantCompanyId(),customerPrice.getCustomerCompanyId());
result.forEach(item->{
//第二步 添加公司id
item.setCustomerCompanyId(customerPrice.getCustomerCompanyId());
item.setMerchantCompanyId(customerPrice.getMerchantCompanyId());
System.out.println(item.toString());
});
//第三步 将改造后的list放入对象 执行添加
customerPrice1.setCustomerPrices(result);
customerPriceService.insert(customerPrice1);
return ResponseFactory.bool().message("导入成功!");
} catch (Exception e){
e.printStackTrace();
throw new BizException("导入失败,请检查参数!");
}
}
乍一看 没啥错误的
但是主要的问题就是在于这个
params.setHeadRows(2);
我这个Excel 表是 标题一行 表头一行
但是我设置了2
很多人和我同样的错误 (因为代码是我直接copy的)
直接用表头将标题也包含进去了,这就会导致这个扫描不到第一列的问题
正确的设置应该是
params.setHeadRows(1);//表头
params.setTitleRows(1);//标题
很多人对表头和标题分不清楚
所以你在有标题的时候,titleRows设置1,如果没有的话,设置0或者不设置(默认是0)
这样问题就解决了