spring MVC 导出excel

本文介绍了一个使用Java在Web应用中导出Excel的方法,包括如何设置HTTP响应头以支持中文文件名,并通过示例代码展示了如何创建Excel工作簿、工作表及单元格等操作。

  1. // 导出excel方法  
  2.  @RequestMapping("exportExcel")  
  3.  public void exportExcel(HttpServletRequest request, HttpServletResponse response)  
  4.  {  
  5.      HttpSession session = request.getSession();  
  6.      session.setAttribute("state"null);  
  7.      // 生成提示信息,  
  8.      response.setContentType("application/vnd.ms-excel");  
  9.      String codedFileName = null;  
  10.      OutputStream fOut = null;  
  11.      try  
  12.      {  
  13.          // 进行转码,使其支持中文文件名  
  14.          codedFileName = java.net.URLEncoder.encode("中文""UTF-8");  
  15.          response.setHeader("content-disposition""attachment;filename=" + codedFileName + ".xls");  
  16.          // response.addHeader("Content-Disposition", "attachment;   filename=" + codedFileName + ".xls");  
  17.          // 产生工作簿对象  
  18.          HSSFWorkbook workbook = new HSSFWorkbook();  
  19.          //产生工作表对象  
  20.          HSSFSheet sheet = workbook.createSheet();  
  21.          for (int i = 0; i <= 30000; i++)  
  22.          {  
  23.              HSSFRow row = sheet.createRow((int)i);//创建一行  
  24.              HSSFCell cell = row.createCell((int)0);//创建一列  
  25.              cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
  26.              cell.setCellValue("测试成功" + i);  
  27.          }  
  28.          fOut = response.getOutputStream();  
  29.          workbook.write(fOut);  
  30.      }  
  31.      catch (UnsupportedEncodingException e1)  
  32.      {}  
  33.      catch (Exception e)  
  34.      {}  
  35.      finally  
  36.      {  
  37.          try  
  38.          {  
  39.              fOut.flush();  
  40.              fOut.close();  
  41.          }  
  42.          catch (IOException e)  
  43.          {}  
  44.          session.setAttribute("state""open");  
  45.      }  
  46.      System.out.println("文件生成...");  
  47.  }  
  48.  @RequestMapping("check")  
  49.  public void check(HttpServletRequest request, HttpServletResponse response)  
  50.  {  
  51.      try  
  52.      {  
  53.          if ("open".equals(request.getSession().getAttribute("state")))  
  54.          {  
  55.              request.getSession().setAttribute("state"null);  
  56.              response.getWriter().write("true");  
  57.              response.getWriter().flush();  
  58.          }  
  59.          else  
  60.          {  
  61.              response.getWriter().write("false");  
  62.              response.getWriter().flush();  
  63.          }  
  64.      }  
  65.      catch (IOException e)  
  66.      {}  
  67.  }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值