业务场景
最近笔者在开发过程中,经常涉及到Excel导入,这边也对横表头文件导入做一个简单的归纳。
解决方案
1、相关依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、方法构建
@PostMapping(value = "/import", headers = "content-type=multipart/form-data")
@ApiOperation(value = "导入")
public ServiceResponse importExcel(MultipartFile file){
List<PscEntity>list = new ArrayList<>();
List<PscInfoEntity>pscInfoList = new ArrayList<>();
Date date = new Date();
try {
//Excel数据解析
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet pscData = workbook.getSheet("ci_psc数据");
for (int rowNum = 1; rowNum <= pscData.getLastRowNum(); rowNum++) {
PscEntity entity = new PscEntity();
Row row = pscData.getRow(rowNum);
entity.setShipName(getStringValue(row.getCell(0)));
//对应字段完善
entity.setPscType(getStringValue(row.getCell(9)));
list.add(entity);
}
Sheet pscInfoData = workbook.getSheet("ci_psc_info数据");
for (int rowNum = 1; rowNum <= pscInfoData.getLastRowNum(); rowNum++) {
PscInfoEntity entity = new PscInfoEntity();
Row row = pscInfoData.getRow(rowNum);
entity.setId(getStringValue(row.getCell(0)));
//对应字段完善
pscInfoList.add(entity);
}
// 关闭工作簿
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
pscService.importExcel(list,pscInfoList);
return ServiceResponse.ok("导入成功");
}
private String getStringValue(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case NUMERIC:
return String.format("%.0f", cell.getNumericCellValue());
case STRING:
default:
return cell.toString();
}
}
尾言
以上便是对常规Excel导入的操作,有需要的同学可以参考下。