@Namespace("/") @ParentPackage("json-default") @Scope("prototype") @Controller public class ReportAction extends BaseAction<WayBill> { //自动注入wayBillService对象 @Autowired private WayBillService wayBillService; @Action(value="report_exportXls") public String exportXls() throws IOException { //查询出满足当前条件的结果数据,获得需要转化成表格的数据,该model是页面传来的数据自动封装成的对象. //该部分逻辑不作介绍 List<WayBill> wayBills = wayBillService.findWayBills(model); //创建excel表格对象 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); HSSFSheet sheet = hssfWorkbook.createSheet("运单数据"); //创建表头行 HSSFRow headRow = sheet.createRow(0); headRow.createCell(0).setCellValue("运输单号"); headRow.createCell(1).setCellValue("寄件人姓名"); headRow.createCell(2).setCellValue("寄件人电话"); headRow.createCell(3).setCellValue("寄件人地址"); headRow.createCell(4).setCellValue("收件人姓名"); headRow.createCell(5).setCellValue("收件人电话"); headRow.createCell(6).setCellValue("收件人地址"); //每一次都循环创建数据列并对表格数据进行遍历插入 for (WayBill wayBill:wayBills ) { HSSFRow rows = sheet.createRow(sheet.getLastRowNum()+1); rows.createCell(0).setCellValue(wayBill.getWayBillNum()); rows.createCell(1).setCellValue(wayBill.getSendName()); rows.createCell(2).setCellValue(wayBill.getSendMobile()); rows.createCell(3).setCellValue(wayBill.getSendAddress()); rows.createCell(4).setCellValue(wayBill.getRecName()); rows.createCell(5).setCellValue(wayBill.getRecMobile()); rows.createCell(6).setCellValue(wayBill.getRecAddress()); } //下载导出部分逻辑 //设置头信息,该ContentType是Excel固定格式 ServletActionContext.getResponse().setContentType("application/vnd.ms-excel"); //文件名 String filename = "运单数据.xls"; //从请求头获取浏览器类型 String agent = ServletActionContext.getRequest().getHeader("user-agent"); //使用工具类对文件名进行处理,使其不会乱码 filename = FileUtils.encodeDownloadFilename(filename,agent); //设置文件名作为下载文件的标识字段 ServletActionContext.getResponse().setHeader( "Content-Disposition","attachment;filename="+filename); //获取输出流对象 ServletOutputStream servletOutputStream = ServletActionContext.getResponse().getOutputStream(); //输出Excel表格 hssfWorkbook.write(servletOutputStream); //关闭 servletOutputStream.close(); return NONE; } }
附:FileUtils
/** * 下载文件时,针对不同浏览器,进行附件名的编码 * * @param filename * 下载文件名 * @param agent * 客户端浏览器 * @return 编码后的下载附件名 * @throws IOException */ public static String encodeDownloadFilename(String filename, String agent) throws IOException { if (agent.contains("Firefox")) { // 火狐浏览器 filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?="; filename = filename.replaceAll("\r\n", ""); } else { // IE及其他浏览器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+"," "); } return filename; }