后台action:
public String exportExcel(){ this.setUserList(this.getUserService().findUserInfosByGroupID(this.getGroupID(), "regTime", 1)); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("用户表"); HSSFRow row = sheet.createRow(0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell(0); cell.setCellValue("账号"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("姓名"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("部门"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("注册时间"); cell.setCellStyle(style); // 第五步,写入实体数据 实际应用中这些数据从数据库得到, for (int i = 0; i < this.getUserList().size(); i++) { row = sheet.createRow(i + 1); UserInfo user = this.getUserList().get(i); // 第四步,创建单元格,并设置值 row.createCell(0).setCellValue(user.getUserName()); row.createCell(1).setCellValue(user.getNickName()); row.createCell(2).setCellValue(user.getCompanyName()); row.createCell( 3).setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(user.getRegTime()));; } // 第六步,将文件存到指定位置 if(this.getGroupID()==0){ this.setExportfilename("全部用户"); //设置fileName }else if (this.getGroupID()==8) { this.setExportfilename("未审核用户"); }else if(this.getGroupID()==9){ this.setExportfilename("已审核用户"); } try { this.setExportfilename(new String(this.getExportfilename().getBytes(),"ISO8859-1")); this.workbook2InputStream(wb); } catch (Exception e) { logger.error(e); return ERROR; } return "exportExcel"; } private void workbook2InputStream(HSSFWorkbook workbook) throws Exception{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); baos.flush(); byte[] aa = baos.toByteArray(); excelStream = new ByteArrayInputStream(aa, 0, aa.length); baos.close(); }
struts.xml 配置
application/vnd.ms-excel excelStream attachment;filename="${exportfilename}.xls" 4024 /WEB-INF/egpage/intercepthtml.jsp