public R uploadFile(MultipartFile file){
StringBuilder sb = new StringBuilder();
try{
//Equipment为我建的实体类
List<Equipment> equipments = this.importBaseExcel(file);
int trueNum = 1;
if(equipments != null && equipments.size()>0){
for(Equipment item:equipments){
boolean save = addEquipment(item).isSuccess();
trueNum++;
if(save != true){
sb.append(trueNum);
}
}
if(StringUtils.isNotEmpty(sb)){
return R.fail("出错行号"+sb+",上传失败");
}else {
return R.success("上传成功");
}
}else {
return R.fail("未获取到导入数据,请检查excel");
}
}catch (Exception e){
e.printStackTrace();
return R.fail(e.getMessage());
}
}
private List<Equipment> importBaseExcel(MultipartFile file) throws Exception{
Workbook workbook = null;
//读取文件内容
workbook = ExcelUtil.getUploadExcelWork(file);
//获取工作表
Sheet sheet = workbook.getSheetAt(0);
//获取首行行号
int firstRowNum = sheet.getFirstRowNum();
//获取尾行行号
int lastRowNum = sheet.getLastRowNum();
List<Equipment> list = null;
if(lastRowNum>0){
list = new ArrayList<>();
Equipment equipment = null;
for(int i = 1; i <=lastRowNum;i++){
Row row = sheet.getRow(i);
equipment = new Equipment();
//获取值
String[] cellValue = getCellValue(row);
//列序
int j = 0;
//此处一共十三项赋值,为了展示省略一部分
//规格型号
equipment.setDeviceSpec(cellValue[j++]);
//出场时间
equipment.setProductionTime(parse(cellValue[j++]));
list.add(equipment);
}
}
return list;
}
//excel中的日期类型单元格也和其它单元格一样,按照string类型来接收获取
//获取行数据
private String[] getCellValue(Row row){
//列数
int j = 13;
String[] cellValue = new String[j];
for(int i=0;i<j;i++){
//获取单元格
//两种不同的excel文件格式,xssf(.xlsx)和hssf(.xls)根据情况使用对应方法
XSSFCell cell = (XSSFCell) row.getCell(i);
//设置单元格类型
cell.setCellType(CellType.STRING);
//获取单元格数据
cellValue[i] = cell.getStringCellValue();
}
return cellValue;
}
//字符串转date
public Date parse(String date){
try {
//获取date类型的关键,使用poi的方法进行转换,将string转换成date
//前面使用了xssf,这里用hssf也能成功?!?xssf好像没这个方法
Date parseDate = HSSFDateUtil.getJavaDate(Double.valueOf(date));
return parseDate;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}