先判断上传文件是否为空
再根据表格最后一行循环
创建行获取单元格并调取封装的时间格式化函数
public void importExcel(MultipartFile file) {
Workbook book = null;
try {
book = WorkbookFactory.create(new BufferedInputStream(file.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet = book.getSheetAt(0);
//判断文件是否为空
if (null == sheet) {
throw new ServiceException("上传内容为空!", 500);
}
//根据最后一行循环
for (int r = 0; r <= sheet.getLastRowNum(); r++) {
//获取行元素
Row row = sheet.getRow(r);
//调用格式化单元格时间函数
getDate(row.getCell(0))
}
}
private Date getDate(Cell c){
//存储时间字符串
String val = "";
//创建一个时间用于赋值返回
Date date = new Date();
//判断单元格数值单元格类型(整数、小数、日期)
if (c.getCellType() == CellType.NUMERIC) {
if (DateUtil.isCellDateFormatted(c)) {
date.setTime(c.getDateCellValue().getTime());
}
}else if (c.getCellType() == CellType.STRING) {//单元格类型为文本
//获取字符串并清空空字符
val = c.getRichStringCellValue().toString().trim();
//时间格式化
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
date.setTime(dateFormat.parse(val).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
return date;
}