Excel 导入时如何下载模板信息(Java)

时间:2023-03-31 09:09:56

大家知道,我们在实现 Excel 上传的时候,会让我们去下载个模板,然后实现导入功能。在此我在这里记录下来,以便后续的使用。。。

首先思考一个问题是 这个模板这么给前台,还有这个模板是这么来的,刚开始的时候,我自己写了个生成Excel模板,然后使用流传到前台,这个时候就出现个问题,但产品经理说是这个模板过于简单,我需要更改,这个就是个问题,难不成我还要更改这个代码,再生成一个使它满足的模板吗,这个实现也可以,就是有点麻烦,需要时间去学。 首先第一个问题,就是这个模板这么来,直接到项目中读取,我们把这个模板放到一个文件夹下。 第二个问题 这个模板这么给前台。先搞点代码。。

/**
* 下载模板信息
* 适用于windows和linux
* @param response
* @param request
* @param templeteName
* @throws IOException
*/
public static void downloadTemplate(HttpServletResponse response,HttpServletRequest request,String templeteName) throws IOException {
OutputStream outp = null;
FileInputStream in = null;
try {
String fileName = templeteName; //要下载的模板文件
if(templeteName!=null){
if(!templeteName.endsWith(".xls")){
fileName = templeteName + ".xls";
}
}
//request.getSession().getServletContext() 相当于tomcat容器
String separator = File.separator; //用于区分是window系统还是liunx系统
String filedownload = "";
if("\\".equals(separator)){
//window 下
filedownload = request.getSession().getServletContext().getRealPath("/WEB-INF/resources/file")+"/"+fileName; // 这个Excel文件存在的路径
filedownload = filedownload.replace("/","\\");
}
if("/".equals(separator)){
//linux下
filedownload = request.getSession().getServletContext().getRealPath("/WEB-INF/resources/file")+"/"+fileName; // 这个Excel文件存在的路径
filedownload = filedownload.replace("\\","/");
}
// 要下载的模板所在的绝对路径
response.reset();
response.addHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(templeteName,"UTF-8"));
//告诉你浏览器下载文件的名称 当为attachment 表示附件下载
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//这里指发送的什么文件类型
outp = response.getOutputStream();
in = new FileInputStream(filedownload);
byte[] b = new byte[2048];
int i = 0;
while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (in != null) {
in.close();
in = null;
}
if (outp != null) {
outp.close();
outp = null;
}
}
}

这个时候大家应该就可以做到啦,如果有疑问或好的办法,请在下方评论,谢谢!