如何下载一个excel文件?
1.设置文件名
String fileName="batch_fund_template.xls";
2设置ContentType
response.setContentType("application/vnd.ms-excel");
3.设置文件路径
String nowPath=request.getSession().getServletContext().getRealPath("/")+"/"+"WEB-INF"+"/"+"template"+"/"+fileName;
4.新建文件对象
File file=new File(nowPath);
5.清空response
response.reset();
6.设置response的header
response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1"));
response.addHeader("Content-Length", ""+file.length());
7.以流的方式下载文件
InputStream fis=new BufferedInputStream(new FileInputStream(nowPath));
byte[] buffer=new byte[fis.available()];
fis.read(buffer);
fis.close();
toClient=new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
整个方法:
@RequestMapping("/file")
public void exportFile(HttpServletRequest request,HttpServletResponse response){
String fileName="batch_fund_template.xls";
exportTemplate(request,response,fileName);
}
public void exportTemplate(HttpServletRequest request,HttpServletResponse response,String fileName){
response.setContentType("application/vnd.ms-excel");
String nowPath=request.getSession().getServletContext().getRealPath("/")+"/"+"WEB-INF"+"/"+"template"+"/"+fileName;
File file=new File(nowPath);
//清空response
response.reset();
OutputStream toClient=null;
try {
//设置response的header
response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1"));
response.addHeader("Content-Length", ""+file.length());
//以流的形式下载文件
InputStream fis=new BufferedInputStream(new FileInputStream(nowPath));
byte[] buffer=new byte[fis.available()];
fis.read(buffer);
fis.close();
toClient=new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
throw new RuntimeException("导出错误");
}finally{
if(toClient!=null){
try {
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}