webwork中用jxl实现list导出为excel的一个例子

在action中配置一个export()方法,代码部分 public String export() throws Exception { if (firstSorter != null) { // 选中排序table head paginationSupport.setSorter(firstSorter); } else { // 保存上次sorter firstSorter = paginationSupport.getSorter(); } queryCriterion = new CommonBizQueryCriterion(queryParams); commonBizs = commonBizService.queryCommonBizs(queryCriterion, new PaginationSupport(10000)); //标题数组 String title[] = {"编号","业务类型","姓名","证件号码","..."}; HttpServletResponse response = ServletActionContext.getResponse(); response.reset(); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("导出结果.xls","UTF-8")); createExcelByCommonBizs(commonBizs,title,response.getOutputStream()); return NONE; } private void createExcelByCommonBizs(List commonBizs, String[] title, OutputStream os) { WritableWorkbook wwb = null; try { wwb = Workbook.createWorkbook(os); WritableSheet sheet = wwb.createSheet("通用业务", 0); // 开始写入第一行(即标题栏) jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(); wcfFC.setBackground(jxl.format.Colour.GRAY_25); for (int i = 0; i < title.length; i++) { sheet.addCell(new Label(i, 0, title[i],wcfFC));// 在Label对象的构造中指明单元格位置(参数依次代表列数、行数、内容 ) } //开始写入内容 for (int row = 0; row < commonBizs.size(); row++) { CommonBiz cb = (CommonBiz) commonBizs.get(row); sheet.addCell(new Label(0, row + 1, cb.getId().toString())); sheet.addCell(new Label(1, row + 1, cb.getBizType().getDescription())); sheet.addCell(new Label(2, row + 1, cb.getCustomerName())); sheet.addCell(new Label(3, row + 1, cb.getIdNum())); //... 可根据需要增加列 } wwb.write(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭Excel工作薄对象 if (wwb != null) { try { wwb.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }

你可能感兴趣的:(Java)