您的位置:首页 > 编程语言 > Java开发

Java 读取Excl文件 (poi-3.13)

2016-01-25 17:28 357 查看
最近做项目遇到了读取Excel数据到数据库做数据的初始化。于是找一个。发现(poi-3.13)可以解决问题。可以解析两种格式(xlsx和xls)

以下是实现的步骤

1.下载poi3.13包,地址(http://poi.apache.org/download.html#POI-3.13)

2.学习APi。

接下来是还是demo来说明问题吧:

1.准备Excel文件:



2.项目的目录结构:



代码实战:

/** 
     * 读取Excel数据 
     * @param file 
     */  
    public List<Student> readExcel(File file){
    List<Student> list = new ArrayList<Student>();
        try {  
            InputStream inputStream = new FileInputStream(file);  
            String fileName = file.getName();  
            Workbook wb = null;  
            if(fileName.endsWith("xls")){  
            //解析xls格式  
                wb = new HSSFWorkbook(inputStream);
            }else if(fileName.endsWith("xlsx")){  
            //解析xlsx格式 
                wb = new XSSFWorkbook(inputStream); 
            }  
            //第一个工作表  
            Sheet sheet = wb.getSheetAt(0);
            //第一行的行号 
            int firstRowIndex = sheet.getFirstRowNum(); 
            //最后一行的行号
            int lastRowIndex = sheet.getLastRowNum();  
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){  
            //获取每一行  
            Row row = sheet.getRow(rIndex);
            Student student = new Student();
                if(row != null){ 
                //获取第一例
                    int firstCellIndex = row.getFirstCellNum();  
                    int lastCellIndex = row.getLastCellNum();  
                    for(int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex ++){  
                    switch (cIndex) {
case 0:
student.setNo1(row.getCell(0).toString());
break;
                        case 1:
                        student.setNo2(row.getCell(1).toString());
break;
                        case 2:
                        student.setNo3(row.getCell(2).toString());
                        break;
                        case 3:
                        student.setNo4(row.getCell(3).toString());
                        break;
                        case 4:
                        student.setNo5(row.getCell(4).toString());
                        break;
                        case 5:
                        student.setNo6(row.getCell(5).toString());
                        break;
                        case 6:
                        student.setNo7(row.getCell(6).toString());
                        break;
           
default:
break;
}
                    }  
                }
                list.add(student);
            }  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
return list;  
    }


结果展示:


就这样了,有问题可以联系我QQ:1561281670
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: