/*传入两个参数:一个是excel文件路径,一个是封装了一个实体信息的类*/
public void outputExcel(File file,UserInfo user) {
try{
WritableWorkbook workbook = null;/*创建工作薄*/
if(file.exists()){ /*查看文件是否存在*/
workbook = Workbook.createWorkbook(file, Workbook.getWorkbook(file));
}else{ /*文件还不存在*/
workbook = Workbook.createWorkbook(new File(file+".xls"));
}
/*创建工作表*/
WritableSheet sheet = workbook.createSheet("用户注册信息表", 0);
jxl.write.Label labelTitle = null;
labelTitle = new jxl.write.Label(0, 0, "用户注册信息表");
sheet.addCell(labelTitle);
jxl.write.Label labelHead =null;
labelHead = new jxl.write.Label(0,1,"注册者姓名");
sheet.addCell(labelHead);
labelHead = new jxl.write.Label(1,1,"注册者密码");
sheet.addCell(labelHead);
labelHead = new jxl.write.Label(2,1,"注册者密码");
sheet.addCell(labelHead);
labelHead = new jxl.write.Label(3,1,"注册者邮箱号");
sheet.addCell(labelHead);
jxl.write.Label label = null;
String str[] = new String[4]; //将要存入excel文件的信息先存入一个字符串数组中。
str[0] =user.getUserName();
str[1] =user.getPassword();
str[2] =user.getSex();
str[3] =user.getEmail();
for(int j = 0;j < 4;j++){
//第一个参数是指列,第二个参数是行,第三个参数是填入的字符串。如果指定填入的格式是数字型,那么还可以用Number
//比如:jxl.write.Number number = new jxl.write.Number (j,i,i+j);sheet.addCell(number);
String rr=str[j];
label = new jxl.write.Label(j,2,rr);
sheet.addCell(label);
}
workbook.write();/*写入数据*/
workbook.close();/*关闭文件*/
}catch(Exception ee){
ee.printStackTrace();
}
} |