java ExcelUtils excel读取工具类

public class ExcelUtils {
    /**
     * 读取excel文件
     *
     * @param inputStream 文件输入流
     * @param headerName  读取文件表头释义
     * @param headerKey   读取文件表头存放key
     * @return
     */
    public static List<Map<String, String>> praseExcel(InputStream inputStream, String[] headerName, String[] headerKey) {
        List<Map<String, String>> insertList = new ArrayList<Map<String, String>>();
        //  rid 读取第一个表格
        //inputStream:输入流,rid:默认读取第一个sheet=0
        ExcelUtil.readBySax(inputStream, 0, (sheetIndex, rowIndex, list) -> {
            Map<String, String> map = new HashMap<>();
            System.out.println("row::  " + rowIndex + "  data:" + list); // 每行的数据 封装在一个列表里面

            if (rowIndex == 0 && list.size() != headerName.length) { //判断第一行表头,和需要读取的表头数据是否一直
                throw new RuntimeException("错误排序格式,正确表头顺序" + headerName.toString());
            }
            if (rowIndex > 0) {//跳过第一行表头 TODO
                if (list == null || list.size() == 0 || list.get(0).equals("")) {//跳过空行
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    map.put(headerKey[i], list.get(i).toString());
                }

            }
            insertList.add(map);
        });
        System.out.println(" jsonlist::" + JSON.toJSONString(insertList));
        return insertList;
    }
}

调用方式:

 public HttpApiResponse<String> orderDivision(
            @ApiParam(value = "总单数",required = true) @RequestParam(value = "total",required = true)  int totalOrder,
            @RequestParam("file") MultipartFile file) throws IOException {

        String name=file.getOriginalFilename();
        System.out.println("读取的文件:: "+name);
        if(name.substring(name.length()-5).equals(".xlsx")||name.substring(name.length()-4).equals(".xls")){

            String[] headerKey=new String[]{"goodsId","price","nums","consignee","address","consigneePhone"};
            String[] headerName=new String[]{"商品id","商品价格","数量","收货人","收货地址","收货电话"};

            List<Map<String, String>>  resultlist= ExcelUtils.praseExcel(file.getInputStream(),headerName,headerKey);

            System.out.println("读取的结果:: "+ JSON.toJSONString(resultlist));

            return HttpApiResponse.success(" import ok");
        }else{
            return  HttpApiResponse.success(" 格式不正确");
        }

    }

使用的jar资源

hutool-poi-5.8.4.jar

gradle 引入:

implementation group: 'cn.hutool', name: 'hutool-poi', version: '5.8.4'

maven 引入

<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-poi -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-poi</artifactId>
    <version>5.8.4</version>
</dependency>

 

posted @ 2022-08-01 15:49  风中有朵云做的鱼  阅读(2637)  评论(0)    收藏  举报