一个小方法,字节流读取.xls文件,将表内容写入到对应数据库表中

来源:互联网 发布:讯飞输入法皮肤知乎 编辑:程序博客网 时间:2024/06/14 01:11

省略了数据库表对应的实体类与插入数据库一行数据的代码,要实现此方法需要在网上下载jxl.jar这个包

public List<Student> readxls(File file) {

List<Student> ls=new ArrayList<Student>();
Workbook workbook=null;

try {
workbook=Workbook.getWorkbook(file);
Sheet sheet=workbook.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
Student student=new Student();
student.setId(Integer.parseInt(sheet.getCell(0,i).getContents()));
student.setName(sheet.getCell(1,i).getContents());
student.setPassword(sheet.getCell(2,i).getContents());
student.setAge(Integer.parseInt(sheet.getCell(3,i).getContents()));
student.setSex(sheet.getCell(4,i).getContents());
ls.add(student);
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
workbook.close();
}
return ls;

}

public class Test {
public static void main(String[] args) {
Dao<Student> ds=StudentManagerFactory.factory();
File file=new File("D:\\学生.xls");
List<Student> list=ds.readxls(file);
for (int i = 0; i < list.size(); i++) {
Student s=list.get(i);
ds.insert(s);
}
}
}

原创粉丝点击