jsp页面下载java工程中已经有的excel模板

最近在做一个excel上传功能,但是同样必须有个下载excel模板,excel模板会存到工程中,点击模板下载,即可下载到本地查看模板样式,如下图:

 

解决思路:

1.在对应的jsp页面添加一个链接:

  下载模板

2.在该jsp页面写对应的js方法:

function downModel(){
var modelFlag = fm.modelFlag.value;
var fileName;
var filePath = fm.strFilePath.value;
if(modelFlag=="1"){
fileName = "policyModel.xls";
}else{
fileName = "claimModel.xls";
}
fm.action =  "/reins/common/DownloadExcelModel.jsp?fileName="+fileName+"&filePath="+filePath;
   fm.submit();
}

其中,modelFlag表示的是一个input隐藏域,一个标志

filePath表示该excel模板保存在该工程中的位置,相关代码如下:


 URL url = getClass().getClassLoader().getResource("/");
 String strFilePath = "";
 if(strFilePath!=null){//保证不为空
    strFilePath+=url.toString();
if(strFilePath.startsWith("file:")&&strFilePath.length()>6){//保证windows环境
strFilePath = strFilePath.substring(6);
}
if(strFilePath.indexOf("WEB-INF/classes")>-1){
strFilePath = strFilePath.substring(0,strFilePath.indexOf("WEB-INF/classes"));
}  
  strFilePath =strFilePath+"common/model";
  System.out.println("strFilePath==========="+strFilePath);
 }

3.将得到的fileName和filePath提交到DownloadExcelModel.jsp页面:

<%page language="java" contentType="text/html; charset=gbk" pageEncoding="gbk"%><%@ page import="java.io.*"%><%
String strFileName = (String)request.getParameter("fileName");
String strFilePath = (String)request.getParameter("filePath");
System.err.println("strFileName=="+strFileName+"====strFilePath===="+strFilePath+"||");
File modelFile = new File("/"+strFilePath,strFileName);
System.err.println(modelFile.getPath()+"=="+modelFile.getName());
if(modelFile.exists()){
FileInputStream is = new FileInputStream(modelFile);
out.clear();
    response.setContentType("application/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\""+strFileName+"\"");
    
    byte [] buf = new byte[4096];
    int nlen=-1;
    do {
    nlen = is.read(buf,0,4096);
    if(nlen>0) {
    response.getOutputStream().write(buf,0,nlen);
    }
    } while(nlen!=-1);
    
    is.close();
    out.close();


}else{
%>

<%

    }

excel下载模板结束

你可能感兴趣的:(jsp页面下载java工程中已经有的excel模板)