excel模板下载(可适用于各种格式文件下载)

来源:互联网 发布:mac快捷键截图 编辑:程序博客网 时间:2024/05/01 19:02
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page language="java" contentType="application/x-msdownload" pageEncoding="utf-8"%>
<%
  //关于文件下载时采用文件流输出的方式处理:
  //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;


  response.reset();//可以加也可以不加
  response.setContentType("application/x-download");


String filedownload = "D:\\MyExcel.xls";
File inFile = new File(application.getRealPath("/")+"temp\\"+"MyExcel.xls");
File inFile1 = new File(this.getClass().getResource("/").getPath()); 
String aa=this.getClass().getResource("").getPath()+"1.jsp";
 String filedisplay = "MyExcel.xls";
 // String filedisplay1 = URLEncoder.encode(filedisplay,"UTF-8");
  response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);


  java.io.OutputStream outp = null;
  java.io.FileInputStream in = null;
  try
  {
  outp = response.getOutputStream();
  in = new FileInputStream(inFile);


  byte[] b = new byte[1024];
  int i = 0;


  while((i = in.read(b)) > 0)
  {
  outp.write(b, 0, i);
  }
//  
outp.flush();
//要加以下两句话,否则会报错
//java.lang.IllegalStateException: getOutputStream() has already been called for //this response  
out.clear();
out = pageContext.pushBody();
}
  catch(Exception e)
  {
  System.out.println("Error!");
  e.printStackTrace();
  }
  finally
  {
  if(in != null)
  {
  in.close();
  in = null;
  }
//这里不能关闭  
//if(outp != null)
  //{
  //outp.close();
  //outp = null;
  //}
  }
%>








<html > 
<head>  
<title></title>  
</head>  
<body>  


</body>  
</html>