java 使用POI读取excel数据

原文:http://doc.okbase.net/0201zcr/archive/161440.html

一、定义

  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
原文地址:https://www.cnblogs.com/shihaiming/p/7205551.html