首先准备jxl.jar.
然后让我们了解了解这个jxl,Excel本来就有工作簿、工作表、单元格等属性,所以我们从数据库导出表格也必须先有工作簿(workbook)、工作表(sheet)、单元格(label)。实现导出表格也是从三个入手。
首先创建一个writeworkbook对象
Writableworkbook book=Workbook.createWorkbook(new File(path));
然后创建工作表sheet对象
WritableSheet sheet=book.createSheet("第一页",0);
创建单元格Label
Label label1=new Label(0,0"XXX");
最后sheet添加单元格
sheet.addCell(label1);
book.write();
book.close();
下面是我的例子。
public String exportExcel(){
String path=ServletActionContext.getServletContext().getRealPath("images/user");
List userList=userService.findAll();
try{
// 打开文件
WritableWorkbook book = Workbook.createWorkbook(new File(path,"apply_users.xls"));
// 定义格式, 字体, 下划线, 斜体, 粗体, 颜色
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
// 创建格式化对象实例
WritableCellFormat totalx2Format = new WritableCellFormat(wf);
// 垂直居中
totalx2Format.setVerticalAlignment(VerticalAlignment.CENTRE);
//自动换行
totalx2Format.setWrap(true);
// 水平居中
totalx2Format.setAlignment(Alignment.CENTRE);
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(" 第一页 ", 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
Label label1 = new Label(0, 0, " 序号 ",totalx2Format);
Label label2 = new Label(1, 0, " 姓名 ",totalx2Format);
Label label3 = new Label(2, 0, " 学院 ",totalx2Format);
Label label4 = new Label(3, 0, " 专业 ",totalx2Format);
Label label5 = new Label(4, 0, " 班级 ",totalx2Format);
Label label6 = new Label(5, 0, " 一卡通号 ",totalx2Format);
Label label7 = new Label(6, 0, " 联系电话 ",totalx2Format);
//给sheet电子版中所有的列设置默认的列的宽度;
sheet.getSettings().setDefaultColumnWidth(30);
// 将定义好的单元格添加到工作表中
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
sheet.addCell(label4);
sheet.addCell(label5);
sheet.addCell(label6);
sheet.addCell(label7);
ACMuser user=new ACMuser();
for (int i = 0; i < userList.size(); i++) {
user=(ACMuser) userList.get(i);
sheet.addCell(new Label(0, i+1, i+1+"",totalx2Format));
sheet.addCell(new Label(1, i+1, user.getUserName(),totalx2Format));
sheet.addCell(new Label(2, i+1, user.getAcademy(),totalx2Format));
sheet.addCell(new Label(3, i+1, user.getMajor(),totalx2Format));
sheet.addCell(new Label(4, i+1, user.getUserClass(),totalx2Format));
sheet.addCell(new Label(5, i+1, user.getCardnumber(),totalx2Format));
sheet.addCell(new Label(6, i+1, user.getPhone(),totalx2Format));
}
book.write();
book.close();
}catch(Exception e){
return "toError";
}
return "toExportExcel";
}