先要导入jxl需要的jar包,然后在触发导出excel时传入集合对象,例如:
public class ToExcel {
public static void excel(List<WenShi> l,HttpServletResponse response) {
ServletOutputStream out = null;
WritableWorkbook wwb = null;
try {
// 导出Excel路径
Date d = new Date();
String s = new SimpleDateFormat("yyyyMMddHHmmss").format(d);
response.setCharacterEncoding("utf-8");
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String("历史数据.xls".getBytes(),"iso-8859-1"));
out = response.getOutputStream();
WritableSheet ws = null;
wwb = Workbook.createWorkbook(out);
ws = wwb.createSheet("sheet1", 0);
// 文字样式
WritableFont wf = new WritableFont(WritableFont.TIMES, 10,
WritableFont.BOLD, false);
WritableCellFormat wcff = new WritableCellFormat(wf);
// 标题
// 第一列第1行(0,0)
Label label1 = new Label(0, 0, "编号", wcff);
// 第一列第2行(0,1)
Label label2 = new Label(1, 0, "环境温度", wcff);
// 第一列第3行(0,2)
Label label3 = new Label(2, 0, "环境湿度", wcff);
Label label4 = new Label(3, 0, "光照强度", wcff);
Label label5 = new Label(4, 0, "土壤温度", wcff);
Label label6 = new Label(5, 0, "土壤湿度", wcff);
Label label7 = new Label(6, 0, "co2浓度", wcff);
// 第一列第4行(0,3)
Label label8 = new Label(7, 0, "时间", wcff);
// 第一列第5行(0,4)
Label label9 = new Label(8, 0, "星期几", wcff);
ws.addCell(label1);
ws.addCell(label2);
ws.addCell(label3);
ws.addCell(label4);
ws.addCell(label5);
ws.addCell(label6);
ws.addCell(label7);
ws.addCell(label8);
ws.addCell(label9);
for (int i = 0; i < l.size(); i++) {
Label l1 = new Label(0, i + 1, l.get(i).getStr("node"));
Label l2 = new Label(1, i + 1, l.get(i).getStr("wen"));
Label l3 = new Label(2, i + 1, l.get(i).getStr("shi"));
Label l4 = new Label(3, i + 1, l.get(i).getStr("sun"));
Label l5 = new Label(4, i + 1, l.get(i).getStr("tuwen"));
Label l6 = new Label(5, i + 1, l.get(i).getStr("tushi"));
Label l7 = new Label(6, i + 1, l.get(i).getStr("co"));
Label l8 = new Label(7, i + 1, l.get(i)
.getTimestamp("timetext").toString());
Label l9 = new Label(8, i + 1, l.get(i).getStr("week"));
ws.addCell(l1);
ws.addCell(l2);
ws.addCell(l3);
ws.addCell(l4);
ws.addCell(l5);
ws.addCell(l6);
ws.addCell(l7);
ws.addCell(l8);
ws.addCell(l9);
}
wwb.write();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
wwb.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}