后台导出方法:
1 /** 2 * 后台导出方法 3 * 利用POI实现数据的批量导出 4 */ 5 public String export() throws Exception{ 6 Connection con = null; 7 try{ 8 con = dbUtil.getCon(); 9 Workbook wb = new HSSFWorkbook(); 10 String headers[] = {"编号", "姓名", "电话", "Email", "QQ"}; 11 ResultSet rs = userDao.userList(con, null); 12 ExcelUtil.fillExcelData(rs, wb, headers); 13 14 //把wb以流的形式输出 15 ResponseUtil.export(ServletActionContext.getResponse(), wb, "导出Excel.xls"); 16 }catch(Exception e){ 17 e.printStackTrace(); 18 }finally{ 19 try{ 20 dbUtil.closeCon(con); 21 dbUtil.closeRs(rs); 22 }catch(Exception e){ 23 e.printStackTrace(); 24 } 25 } 26 27 return null; 28 }
处理excel的Util:
1 /** 2 * 处理Excel的util 3 */ 4 public class ExcelUtil{ 5 6 public static void fillExcelData(ResultSet rs, Workbook wb, String[] headers) throws Exception{ 7 int rowIndex = 0; 8 Sheet sheet = wb.createSheet(); 9 Row row = sheet.createRow(rowIndex++); 10 for(int i=0; i<headers.length; i++){ 11 row.createCell(i).setCellValue(headers[i]); 12 } 13 14 //这里假设的是头的列数和数据的列数是一样的 15 while(rs.next()){ 16 row = sheet.createRow(rowIndex++); 17 for(int i=0; i<headers.length; i++){ 18 row.createCell(i).setCellValue(rs.getObject(i+1).toString()); 19 } 20 } 21 } 22 }
ResponseUtil以流的形式导出Workbook:
1 /** 2 * ResponseUtil相应util 3 */ 4 public class ResponseUtil{ 5 public static void write(HttpServletResponse response, Object o) throws Exception{ 6 response.setContentType("text/html;charset=utf-8"); 7 PrintWriter pw = response.getWriter(); 8 pw.print(o.toString()); 9 pw.flush(); 10 pw.close(); 11 } 12 13 /** 14 *导出Excel 15 * fileName: 导出的文件名 16 */ 17 public static void export(HttpServletResponse response, Workbook wb, String fileName) throws Exception{ 18 response.setHeader("Content-Disposition", "attachment;filename=" 19 +new String(fileName.getBytes("utf-8"), "iso8859-1")); 20 response.setContentType("application/ynd.ms-excel;charset=UTF-8"); 21 OutputStream out = response.getOutputStream(); 22 wb.write(out); 23 out.flush(); 24 out.close(); 25 } 26 }
导出的Excel: