/** * 读取数据库文件生成Excel * */ public String paymentsToExcel(List<VerifyCode> verifyCodesList) { //verifyCodesList是读取数据库数据存入List中 String sheetName = "随机码列表"; String xlsName = System.currentTimeMillis()+".xls"; //创建Excel的工作册 Workbook,对应到一个excel文档 HSSFWorkbook workbook = new HSSFWorkbook(); //创建Excel的工作sheet,对应到一个excel文档的tab HSSFSheet sheet = workbook.createSheet(); workbook.setSheetName(0,sheetName); HSSFRow row= sheet.createRow((short)0);; HSSFCell cell; int nColumn=fields.length; //excel列名 row = sheet.createRow((short)0); for(int j=1;j<=nColumn;j++) { //序列ID cell = row.createCell(j-1); cell.setCellType(HSSFCell.CELL_TYPE_STRING); Object objReturnValue = fieldsName[j-1] ; cell.setCellValue(objReturnValue+""); } int iRow=1; //写入各条记录,每条记录对应Excel中的一行 for (LicaiVerifyCode liCaiVerifyCode:verifyCodesList){ row = sheet.createRow((short)iRow); for(int j=1;j<=nColumn;j++) { //序列ID cell = row.createCell(j-1); String objReturnValue = "" ; cell.setCellType(HSSFCell.CELL_TYPE_STRING); try { Method currentMethod = liCaiVerifyCode.getClass().getMethod(fields[j-1]); if(fields[j-1].equals("getEffectiveTime")||fields[j-1].equals("getFailureTime")||fields[j-1].equals("getCreateTime")||fields[j-1].equals("getLastModifyTime")){ SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss"); objReturnValue = sd.format(currentMethod.invoke(liCaiVerifyCode)); }else{ objReturnValue = String.valueOf(currentMethod.invoke(liCaiVerifyCode)); } } catch (Exception ex) { ex.printStackTrace(); } cell.setCellValue(objReturnValue+""); } iRow++; } try { //输出 ActionContext context = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE); response.setHeader("Content-disposition", "attachment; filename="+xlsName);//设定输出文件头 response.setContentType("application/vnd.ms-excel");//定义输出类型 OutputStream os = response.getOutputStream(); workbook.write(os); os.close(); } catch (Exception ex) { ex.printStackTrace(); } return SUCCESS; }
读取数据库文件用POI生成Excel
读取数据库中的数据导出成Excel在页面可供用户下载,代码如下:
猜你喜欢
转载自mjc410621.iteye.com/blog/2092797
周排行