excel表格数据导入java封装类
需要导入的pom文件依赖
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
后台代码
@Operation(name="添加到账导入信息")
@RequestMapping("upload")
@ResponseBody
public Map<String, Object> addPayment(ReceiveThePayment receiveThePayment,@RequestParam MultipartFile file) throws Exception{
Map<String, Object> map = new HashMap<String,Object>(16);
XSSFWorkbook workbook =null;
CommonsMultipartFile cmf= (CommonsMultipartFile)file;
DiskFileItem dfi=(DiskFileItem) cmf.getFileItem();
File fo=dfi.getStoreLocation();
workbook = new XSSFWorkbook(FileUtils.openInputStream(fo));
XSSFSheet sheet = workbook.getSheetAt(0);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
try {
for(int i=firstRowNum+1;i<=lastRowNum;i++){
XSSFRow row = sheet.getRow(i);
XSSFCell date = row.getCell(0);
if(date!=null){
date.setCellType(Cell.CELL_TYPE_STRING);
String stringCellValue = date.getStringCellValue();
Date parse = new SimpleDateFormat("yyyyMMdd").parse(stringCellValue);
Instant instant = parse.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
receiveThePayment.setDate((localDateTime));
}
XSSFCell consignor = row.getCell(1);
if(consignor!=null){
consignor.setCellType(Cell.CELL_TYPE_STRING);
receiveThePayment.setConsignor((consignor.getStringCellValue()));
}
XSSFCell arrivalAmount = row.getCell(2);
if(arrivalAmount!=null){
arrivalAmount.setCellType(Cell.CELL_TYPE_STRING);
String stringCellValue = arrivalAmount.getStringCellValue();
Double result = Double.parseDouble("".equals(stringCellValue)?"0.00":stringCellValue);
receiveThePayment.setArrivalAmount(result);
}
map.put("status",true);
map.put("msg", "操作成功");
}else {
map.put("status",false);
map.put("msg", "操作失败");
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}