springboot读取excel数据-简单代码

springboot整合poi读取excel数据

废话不多说,直接上代码

方法类

public static Map> readExcelContentz(MultipartFile file) throws Exception{
    Map> content = new HashMap>();
        // 上传文件名
        Workbook wb = getWb(file);
        if (wb == null) {
            throw new Exception("Workbook对象为空!");
        }
        Sheet sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        Row row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map cellValue = new HashMap();
            while (j < colNum) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(j, obj);
                j++;
            }
            content.put(i, cellValue);

    }
    return content;
}
//根据Cell类型设置数据
private static Object getCellFormatValue(Cell cell) {
    Object cellvalue = "";
    if (cell != null) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
            case Cell.CELL_TYPE_FORMULA: {
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    cellvalue = date;
                } else {
                    cellvalue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            }
            case Cell.CELL_TYPE_STRING:
                cellvalue = cell.getRichStringCellValue().getString();
                break;
            default:
               cellvalue = "";
        }
    } else {
        cellvalue = "";
    }
    return cellvalue;
}

private static Workbook getWb(MultipartFile mf){
    String filepath = mf.getOriginalFilename();
    String ext = filepath.substring(filepath.lastIndexOf("."));
    Workbook wb = null;
    try {
        InputStream is = mf.getInputStream();
        if(".xls".equals(ext)){
            wb = new HSSFWorkbook(is);
        }else if(".xlsx".equals(ext)){
            wb = new XSSFWorkbook(is);
        }else{
            wb=null;
        }
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException", e);
    } catch (IOException e) {
        logger.error("IOException", e);
    }
    return wb;
}

service层

public Map<Integer, Map<Integer,Object>> addCustomerInfo(MultipartFile file) {
    Map<Integer, Map<Integer,Object>> map = new HashMap<>();
    try {
        map = ReadExcelUtil.readExcelContentz(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //excel数据存在map里,map.get(0).get(0)为excel第1行第1列的值,此处可对数据进行处理
}

controller层

@PostMapping
public String add(@RequestParam("file")MultipartFile file){
    Map<Integer, Map<Integer,Object>> map = customerService.addCustomerInfo(file);
    return "success";
}

使用appiza进行处理这里写图片描述

你可能感兴趣的:(springboot读取excel数据-简单代码)