`

java 响应客户端下载excel文件请求

阅读更多

涉及jar文件:struts1.2   poi(操作excel)。

 

功能描述:将相关的数据保存在excel中响应客户端。整个过程中不能在服务器端生存excel文件。

 

主要代码如下:

public ActionForward down(ActionMapping mapping,ActionForm form,HttpServletRequest reuqest,HttpServletResponse response)throws IOException
 {


  try{
   //取得输出流
   OutputStream out = response.getOutputStream();
   //清空输出流
   response.reset();

   //设置响应头和下载保存的文件名
   response.setHeader("content-disposition","attachment;filename="+"cc.xls");
   //定义输出类型
   response.setContentType("APPLICATION/msexcel");
           
   HSSFWorkbook wb=new HSSFWorkbook();
   HSSFSheet sheet=wb.createSheet("new sheet");
   HSSFRow row=sheet.createRow((short)0);
   HSSFCell cell=row.createCell((short)0);

   cell.setCellValue(1);
   row.createCell((short)1).setCellValue(1.2);
   row.createCell((short)2).setCellValue("test");
   row.createCell((short)3).setCellValue(true);
          
   wb.write(out);

   out.close();

   //这一行非常关键,否则在实际中有可能出现莫名其妙的问题!!!
   response.flushBuffer();//强行将响应缓存中的内容发送到目的地 

  }catch(Exception e){
        e.printStackTrace();
  }


   return mapping.getInputForward();

 

 }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics