``` public boolean ReadFromExcel(JFrame frame) {
List<Student> list = new ArrayList<Student>();
int count = 0 ;
int result = 0 ;
File file = null ;
JFileChooser fileChooser = new JFileChooser();
jxl.Workbook readwb = null;
try {
fileChooser.setApproveButtonText("确定");
fileChooser.setDialogTitle("打开文件");
result = fileChooser.showOpenDialog(frame);
if(result == JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile() ;
}else if(result == JFileChooser.CANCEL_OPTION){
int result1 = JOptionPane.showConfirmDialog(null, "你未选择文件确定要退出吗?","提示", JOptionPane.INFORMATION_MESSAGE);
if(result1 == 0){
JOptionPane.showMessageDialog(null, "退出成功","提示", JOptionPane.INFORMATION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "操作有误!","警告", JOptionPane.ERROR_MESSAGE);
}
if(file != null){
System.out.println(file.getPath());
readwb = Workbook.getWorkbook(new FileInputStream(file));
// Sheet的下标是从0开始
Sheet readsheet = readwb.getSheet(0); // 获取第一张Sheet表
int rsColumns = readsheet.getColumns(); // 获取Sheet表中所包含的总列数
int rsRows = readsheet.getRows(); // 获取Sheet表中所包含的总行数
System.out.println(rsColumns+" "+rsRows);
for (int i = 1; i < rsRows; i++) {
Student stu = new Student();
for (int j = 0; j < rsColumns; j++) {
System.out.println(j+" "+i);
Cell cell = readsheet.getCell(j, i); // 获取指定单元格的对象引用
System.out.println(cell.getContents());
switch (j) {
case 0:
stu.setNumber(cell.getContents());
break;
case 1:
stu.setName(cell.getContents());
break;
case 2:
// System.out.println(Integer.parseInt(cell.getContents()));
stu.setAge(Integer.parseInt(cell.getContents()));
break;
case 3:
stu.setSex(cell.getContents());
break;
case 4:
stu.setProvince(cell.getContents());
break;
case 5:
stu.setMajor(cell.getContents());
break;
case 6:
stu.setPhoneNum(cell.getContents());;
break;
case 7:
stu.setBirthday(cell.getContents());
break;
case 8:
stu.setHabit(cell.getContents());
break;
default:
break;
}
}
list.add(stu);
System.out.println(stu);
readwb.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0 ;i< list.size() ;i++){
// System.out.println("1111");
Student stu1 = list.get(i) ;
if(!checkStudent(stu1)){
count++ ;
try{
// System.out.println("1111");
add(stu1) ;
}catch (Exception e) {
e.printStackTrace();
}
}
}
JOptionPane.showMessageDialog(null, "成功读取"+count+"条数据到数据库中","提示", JOptionPane.INFORMATION_MESSAGE);
return true ;
}
上面代码中,是通过文件选择器来选择文件
![这个是异常的图片](https://img-ask.csdn.net/upload/201612/11/1481441815_126992.png)
![这个是表的图片](https://img-ask.csdn.net/upload/201612/11/1481441826_895589.png)