excel上传.xls版本,xlsx版本换成 XSSFWorkbook的方法即可
@RequestMapping("/secondInventoryUp")
@ResponseBody
public String secondInventoryUp( @RequestParam(value = "fileImport", required = false) MultipartFile file,HttpServletRequest request){
if (null != file && !file.isEmpty()) {
try {
String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE; // 文件上传路径
String fileName = FileUpload.fileUp(file, filePath, "userexcel"); // 执行上传
List<Map<String,Object>> mapList = new ArrayList(); // 执行读EXCEL操作,读出的数据导入List
File target = new File(filePath, fileName);
FileInputStream fi = new FileInputStream(target);
HSSFWorkbook wb = new HSSFWorkbook(fi);
HSSFSheet sheet = wb.getSheetAt(0);
int firstRowIndex = sheet.getFirstRowNum()+3; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
//读取字段名
List<String> list = new ArrayList<>();
for (int i = sheet.getRow(firstRowIndex).getFirstCellNum();i<sheet.getRow(firstRowIndex).getLastCellNum();i++){
Cell cell = sheet.getRow(firstRowIndex).getCell(i);
list.add(cell.toString());
}
firstRowIndex++;
//将值塞入集合
boolean flag = true;
List<Map<String,Object>> excelList = new ArrayList<>();
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
Map<String,Object> excelMap = new HashMap<>();
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if ("数量合计:".equals(cell.toString())){
flag = false;
break;
}
if (cell != null) {
excelMap.put(list.get(cIndex),cell.toString());
}
}
}
if (flag == false){
break;
}
excelList.add(excelMap);
}
//对上传的数据excelList 进行具体操作
} catch (Exception e) {
log.error(e.toString(), e);
return "上传失败!";
}
}
return "上传成功!";
}