zoukankan      html  css  js  c++  java
  • java 使用POI批量导入excel数据

    一、定义

      Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

    二、所需jar包

    三、简单的一个读取excel的demo

    1、读取文件方法

         /**
         * 读取出filePath中的所有数据信息
         * @param filePath excel文件的绝对路径
         * 
         */
        
        public static void getDataFromExcel(String filePath)
        {
            //String filePath = "E:\123.xlsx";
            
            //判断是否为excel类型文件
            if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
            {
                System.out.println("文件不是excel类型");
            }
            
            FileInputStream fis =null;
            Workbook wookbook = null;
            
            try
            {
                //获取一个绝对地址的流
                  fis = new FileInputStream(filePath);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
           
            try 
            {
                //2003版本的excel,用.xls结尾
                wookbook = new HSSFWorkbook(fis);//得到工作簿
                 
            } 
            catch (Exception ex) 
            {
                //ex.printStackTrace();
                try
                {
                    //2007版本的excel,用.xlsx结尾
                    
                    wookbook = new XSSFWorkbook(fis);//得到工作簿
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            //得到一个工作表
            Sheet sheet = wookbook.getSheetAt(0);
            
            //获得表头
            Row rowHead = sheet.getRow(0);
            
            //判断表头是否正确
            if(rowHead.getPhysicalNumberOfCells() != 3)
            {
                System.out.println("表头的数量不对!");
            }
            
            //获得数据的总行数
            int totalRowNum = sheet.getLastRowNum();
            
            //要获得属性
            String name = "";
            int latitude = 0;
            
           //获得所有数据
            for(int i = 1 ; i <= totalRowNum ; i++)
            {
                //获得第i行对象
                Row row = sheet.getRow(i);
                
                //获得获得第i行第0列的 String类型对象
                Cell cell = row.getCell((short)0);
                name = cell.getStringCellValue().toString();
                
                //获得一个数字类型的数据
                cell = row.getCell((short)1);
                latitude = (int) cell.getNumericCellValue();
                
                System.out.println("名字:"+name+",经纬度:"+latitude);
                
            }
        }

    2、测试

    public static void main(String[] args) 
        {        
            getDataFromExcel("E:"+ File.separator +"123.xlsx");
        }

    3、原始数据

    4、结果

    名字:A1,经纬度:1
    名字:A2,经纬度:2
    名字:A3,经纬度:3
    名字:A4,经纬度:4
    名字:A5,经纬度:5
    名字:A6,经纬度:6
    名字:A7,经纬度:7
    名字:A8,经纬度:8
    名字:A9,经纬度:9
    名字:A10,经纬度:10
    名字:A11,经纬度:11

    四、注意事项

    1、运用多态,excel主要有.xls结尾(2003版本)和. xlsx(2007版本)两种类型结尾的文件,分别需要用HSSFWorkbook对象对.xls文件进行读取,用XSSFWorkbook对象对.xlsx文件进行读取,直接使用他们共同的父类Workbook进行初始化对象有利于代码的易用性。

    2、通过流的方式初始化工作簿对象(Workbook),可以通过new XSSFWorkbook(文件绝对路径)和new XSSFWorkbook(输入流)两种方式初始化对象,但是假如我们只是通过修改.xls文件的后缀名为.xlsx,这样子当我们用new XSSFWorkbook(文件绝对路径)来读取文件的时候就会报错,因为他本身就不是一个2007版本的excel类型的文件,读取会报错;假如我们是通过流的方式的话,可以避免这种情况,我们即使你修改了文件的后缀名,我们依然在初始化的时候能获取到该对象是.xls类型文件,使用HSSFWorkbook对象进行处理,即能得出正确的结果。

     五、增强版

      添加了判断表头是否符合规范,允许表头对象的位置不同。进行了一定的解耦合。

        /**
         *     
         * @param cell 一个单元格的对象
         * @return 返回该单元格相应的类型的值
         */
        public static Object getRightTypeCell(Cell cell){
        
            Object object = null;
            switch(cell.getCellType())
            {
                case Cell.CELL_TYPE_STRING :
                {
                    object=cell.getStringCellValue();
                    break;
                }
                case Cell.CELL_TYPE_NUMERIC :
                {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    object=cell.getNumericCellValue();
                    break;
                }
                    
                case Cell.CELL_TYPE_FORMULA :
                {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    object=cell.getNumericCellValue();
                    break;
                }
                
                case Cell.CELL_TYPE_BLANK :
                {
                    cell.setCellType(Cell.CELL_TYPE_BLANK);
                    object=cell.getStringCellValue();
                    break;
                }
            }
            return object;
        }    
    /**
         * 读取出filePath中的所有数据信息
         * @param filePath excel文件的绝对路径
         * 
         */
        
        public static void getDataFromExcel2(String filePath)
        {
            List<Map<String,Integer>> list = new ArrayList<Map<String, Integer>>();
            //判断是否为excel类型文件
            if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
            {
                System.out.println("文件不是excel类型");
            }
            
            FileInputStream fis =null;
            Workbook wookbook = null;
            int flag = 0;
            
            try
            {
                //获取一个绝对地址的流
                  fis = new FileInputStream(filePath);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
           
            try 
            {
                //2003版本的excel,用.xls结尾
                wookbook = new HSSFWorkbook(fis);//得到工作簿
                 
            } 
            catch (Exception ex) 
            {
                //ex.printStackTrace();
                try
                {
                    //2007版本的excel,用.xlsx结尾
                    
                    wookbook = new XSSFWorkbook(filePath);//得到工作簿
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            //得到一个工作表
            Sheet sheet = wookbook.getSheetAt(0);
            
            //获得表头
            Row rowHead = sheet.getRow(0);
            
          //根据不同的data放置不同的表头
            Map<Object,Integer> headMap = new HashMap<Object, Integer>();
            
            
            //判断表头是否合格  ------------------------这里看你有多少列
            if(rowHead.getPhysicalNumberOfCells() != 2)
            {
                System.out.println("表头列数与要导入的数据库不对应");
            }
            
            try
            {
                //----------------这里根据你的表格有多少列
                while (flag < 2)
                {
                    Cell cell = rowHead.getCell(flag);
                    if (getRightTypeCell(cell).toString().equals("基站名"))
                    {
                        headMap.put("jizhan", flag);
                    }
                    if (getRightTypeCell(cell).toString().equals("经纬度"))
                    {
                        headMap.put("jingweidu", flag);
                    }
                    flag++;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("表头不合规范,请修改后重新导入");
            }
            
            
            //获得数据的总行数
            int totalRowNum = sheet.getLastRowNum();
            
            
            
            //要获得属性
            String name = "";
            double latitude = 0;
            
            if(0 == totalRowNum)
            {
                System.out.println("Excel内没有数据!");
            }
            
            Cell cell_1 = null,cell_2 = null;
            
           //获得所有数据
            for(int i = 1 ; i <= totalRowNum ; i++)
            {
                //获得第i行对象
                Row row = sheet.getRow(i);
                
                try
                {
                    cell_1 = row.getCell(headMap.get("jizhan"));
                    cell_2 = row.getCell(headMap.get("jingweidu"));
                } catch (Exception e)
                {
                    e.printStackTrace();
                    System.out.println("获取单元格错误");
                }
                
                try
                {
                    //基站
                    name = (String) getRightTypeCell(cell_1);
                    //经纬度
                    latitude = (Double) getRightTypeCell(cell_2);
                } catch (ClassCastException e)
                {
                    e.printStackTrace();
                    System.out.println("数据不全是数字或全部是文字!");
                }
                System.out.println("名字:"+name+",经纬度:"+latitude);
                
            }
        }
        

    异常情况:

    应将下面这段代码

    try 
            {
                //2003版本的excel,用.xls结尾
                wookbook = new HSSFWorkbook(fis);//得到工作簿
                 
            } 
            catch (Exception ex) 
            {
                //ex.printStackTrace();
                try
                {
                    //2007版本的excel,用.xlsx结尾
                    
                    wookbook = new XSSFWorkbook(fis);//得到工作簿
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

    改为:

            try 
            {
                //2003版本的excel,用.xls结尾
                wookbook = new HSSFWorkbook(fis);//得到工作簿
                 
            } 
            catch (Exception ex) 
            {
                //ex.printStackTrace();
                try
                {
                    //这里需要重新获取流对象,因为前面的异常导致了流的关闭—————————————————————————————加了这一行
                     fis = new FileInputStream(filePath);
                    //2007版本的excel,用.xlsx结尾
                    
                    wookbook = new XSSFWorkbook(filePath);//得到工作簿
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

    解析:因为前面异常导致了流的关闭,所以需要重新创建一个流对象。

  • 相关阅读:
    kotlin入门
    android 组件化、插件化、热更新
    hadoop的心跳回忆
    [转] 支持向量机SVM的理解
    HDFS的block Id与generation stamp
    【Z】awk中使用shell的环境变量
    ceph相关
    华为手机C8812连不上豌豆荚等手机助手——解决方法
    【亲测】fatal error C1010: unexpected end of file while looking for precompiled head
    JOI Open 中一些没有题解的题的简要题解
  • 原文地址:https://www.cnblogs.com/0201zcr/p/4656779.html
Copyright © 2011-2022 走看看