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

java中用jxl方式读取Excel

2013-11-10 19:33 417 查看
首先导入jxl的包,可以在网上下载

例如 读取一份存储有学生信息的Excel

public static List<Student> readExcel(String filePath){

  

  List<Student> students = new ArrayList<Student>();

    try { 

                 // 创建输入流,读取Excel 

                 InputStream is = new FileInputStream(filePath); 

                // jxl提供的Workbook类 

                Workbook wb = Workbook.getWorkbook(is);

                // Excel的页签数量 

                int sheet_size = wb.getNumberOfSheets(); 

                 for (int index = 0; index < sheet_size; index++) { 

                     // 每个页签创建一个Sheet对象 

                     Sheet sheet = wb.getSheet(index); 

                     // sheet.getRows()返回该页的总行数 

                     for (int i = 0; i < sheet.getRows(); i++) {  //代表行

                         // sheet.getColumns()返回该页的总列数 

                      Student  student = new Student();

                      //第一行为字段,所以跳过

                      if(i==0){

                       continue;

                      }

                       for (int j = 0; j < sheet.getColumns(); j++) {  //代表列

                             String cellinfo = sheet.getCell(j, i).getContents(); 

                            int  m =   sheet.getCell(j, i).getColumn();

                            switch(m){

                            case 0:

                             student.setNumber(Integer.parseInt(cellinfo));

                             break;

                            case 1:

                             student.setName(cellinfo);

                             break;

                            case 2:

                             student.setSex(cellinfo);

                             break;

                            case 3:

                             student.setAge(Integer.parseInt(cellinfo));

                             break;

                            case 4:

                             student.setAddress(cellinfo);

                             break;

                            }

                            // System.out.println(cellinfo); 

                         } 

                       students.add(student);

                     } 

                } 

          } catch (FileNotFoundException e) { 

                 e.printStackTrace(); 

             } catch (BiffException e) { 

                 e.printStackTrace(); 

             } catch (IOException e) { 

                 e.printStackTrace(); 

             }

             System.out.print(students.size());

  return students;

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