countryRecord not found 引发的读取Excel的三种方法

前言,这次读取excel可是大费周折,由于某些原因,读取excel显然没有那么简单了,待我细细说来


1.首先使用easypoi读取excel,这种方法可谓是百试不爽,但唯独这一次,凉了,原因是,我读取的excel是gp服务生成的,然后再读取的时候报错没有国家码,countryRecord not found

2.然后换成用jxl.jar的方式去读excel ,具体使用方法如下
首先下载jxl.jar
然后项目本地引入jar
接下来看一下代码

  //1:创建workbook
        jxl.Workbook workbook= null;
        try {
       //path为excel路径
            workbook = jxl.Workbook.getWorkbook(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        //2:获取第一个工作表sheet
        Sheet sheet=workbook.getSheet(0);
        //3:获取数据
        System.out.println("行:"+sheet.getRows());
        System.out.println("列:"+sheet.getColumns());
        List<Map<String,Object>> list = new ArrayList<>();
        int index = 0;
        int index2 = 0;
        int index3 = 0;
        Map<String, Object> map = new HashMap<>();
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        List<String> list3 = new ArrayList<>();

        for(int i=0;i<sheet.getRows();i++){

            for(int j=0;j<sheet.getColumns();j++){

                Cell cell= sheet.getCell(j,i);

               
                System.out.print(((jxl.Cell) cell).getContents()+" ");
            }
            System.out.println();
        }

会输出每个单元格的值,然后根据自己的需要进行封装数据,(对象或者集合中)

2.本以为解决问题了,可没想到excel单元格中有下图数据

使用上面方法读取到单元格的数据都是0,竟然都是零!无奈之下换了第三种方法

3.使用poi读取excel

首先再pom文件中添加poi的依赖

     <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>RELEASE</version>
        </dependency>

代码如下

   String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List<List<String>> lists = new ArrayList<List<String>>();
        //读取excel文件
        InputStream is = null;
        List<Map<String,Object>> listMap = null;
        Map map = new HashMap();
        try {
            is = new FileInputStream(path);
            //获取工作薄
            Workbook wb = null;
            if (fileType.equals("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                return null;
            }

            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //第一行为标题

            for (Row row : sheet) {
                ArrayList<String> list = new ArrayList<String>();
                for (Cell cell : row) {
                    //根据不同类型转化成字符串
                    cell.setCellType(CellType.STRING);
                    list.add(cell.getStringCellValue());
                }
                lists.add(list);
            }

根据自己的需要再进行方法的丰富,至此就算完了。