1、依赖jar包
jxl.jar
2、导入
publicstaticvoid main(String[] args){
/**Excel文件转JavaBean**/
List<StuEntity> listExcel=StuService.getAllByExcel("d://book.xls");
//保存到数据库
- ...
}
publicstaticList<StuEntity> getAllByExcel(String file){
List<StuEntity> list=newArrayList<StuEntity>();
try{
/**Excel文件转工作薄**/
Workbook rwb=Workbook.getWorkbook(newFile(file));
Sheet rs=rwb.getSheet("Test Shee 1");//获取表
int clos=rs.getColumns();//获取列
int rows=rs.getRows();//获取行
/**工作薄转JavaBean**/
for(int i =1; i < rows; i++){
for(int j =0; j < clos; j++){
String id=rs.getCell(j++, i).getContents();//获取单元格
String name=rs.getCell(j++, i).getContents();
String sex=rs.getCell(j++, i).getContents();
String num=rs.getCell(j++, i).getContents();
list.add(newStuEntity(Integer.parseInt(id), name, sex,Integer.parseInt(num)));
}
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
3、导出
publicstaticvoid main(String[] args){
try{
/**JavaBean**/
List<StuEntity> list=StuService.getAllByDb();
Label labelId=newLabel(0,0,"编号(id)");//表示第
Label labelName=newLabel(1,0,"姓名(name)");
Label labelSex=newLabel(2,0,"性别(sex)");
Label labelNum=newLabel(3,0,"薪水(num)");
/**创建Excel文件**/
String fileName ="D://book.xls";
File file=newFile(fileName);
if(!file.exists()){
file.createNewFile();
}
/**Excel文件转工作薄**/
WritableWorkbook wwb =Workbook.createWorkbook(file);
/**创建表**/
WritableSheet ws = wwb.createSheet("Test Shee 1",0);
ws.addCell(labelId);//添加单元格
ws.addCell(labelName);
ws.addCell(labelSex);
ws.addCell(labelNum);
for(int i =0; i < list.size(); i++){
Label labelId_i=newLabel(0, i+1, list.get(i).getId()+"");
Label labelName_i=newLabel(1, i+1, list.get(i).getName());
Label labelSex_i=newLabel(2, i+1, list.get(i).getSex());
Label labelNum_i=newLabel(3, i+1, list.get(i).getNum()+"");
ws.addCell(labelId_i);
ws.addCell(labelName_i);
ws.addCell(labelSex_i);
ws.addCell(labelNum_i);
}
//写进文档
wwb.write();
// 关闭Excel工作簿对象
wwb.close();
}catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}