KR673
3/18/2020 - 6:40 AM

从excel表格中分页读取数据

[Paging read data from excel] 从excel表格中分页读取数据 , 格式为 第一行为表头, 剩下的是数据

public static Map<String, Object> getExcelDataByPage(String path, List<String> fields, Integer page, Integer limit) throws  InvalidFormatException {

        try(FileInputStream in = new FileInputStream(path)){
            Workbook wb = WorkbookFactory.create(in);
            Sheet sheet = wb.getSheetAt(0);

            if (Objects.isNull(sheet)) {
                return new HashMap<>();
            }
            List<Map> resultList = new ArrayList<>();

            //取出从step开始, limit条数据, 需要跳过第一行表头
            int step = page > 0 ? (page - 1) * limit + 2 : 2;
            limit = step + limit;
            int rowNumber = 1;

            // 获取数据总行数, 跳过空行
            Integer count = 0;
            for (Row cells : sheet) {
                if (cells.getLastCellNum() < 0){
                    continue;
                }
                count++;
            }

            // 数据字段关联
            for (Row rowData : sheet) {

                if (rowData.getLastCellNum() < 0){
                    continue;
                }

                if (rowNumber >= step) {
                    //遍历每一行数据
                    Map<String, Object> map = new HashMap<>();
                    for (Cell cell : rowData) {
                        if(cell.getColumnIndex() < fields.size()){
                            // 添加字段和数据的映射关系
                            map.put(fields.get(cell.getColumnIndex()), String.valueOf(cell));
                        }
                    }
                    resultList.add(map);
                }
                rowNumber++;
                if(rowNumber >= limit){
                    break;
                }
            }

            HashMap<String, Object> result = new HashMap<>();
            result.put("data", resultList);
            result.put("count", count - 1);
            return result;
            
        }catch (IOException e){
            e.printStackTrace();
            return new HashMap<>() {{
                put("data","文件不存在");
                put("count", 0);
            }};
        }
    }
public static List<String> getFields(String path) throws InvalidFormatException {

        try(FileInputStream in = new FileInputStream(path)) {
            List<String> result = new ArrayList<>();
            Workbook wb = WorkbookFactory.create(in);
            Sheet sheet = wb.getSheetAt(0);

            if (sheet != null) {
                for (Row rowData : sheet) {
                    for (Cell cell : rowData) {
                        result.add(cell.toString());
                    }
                    break;
                }
            }
            return result;
        } catch (IOException e){
            return new ArrayList<>();
        }
    }