欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot下载excel模板

程序员文章站 2022-03-26 08:43:32
在网上找了半天,获取springboot resource下面的文件,各种实验,最终解决了,废话不说直接上代码 /** * 描述:下载外部案件导入模板 * @throws Exception */ @RequestMapping(value = "/downloadExcel") @Response ......

在网上找了半天,获取springboot resource下面的文件,各种实验,最终解决了,废话不说直接上代码

 

/**
* 描述:下载外部案件导入模板
* @throws exception
*/
@requestmapping(value = "/downloadexcel")
@responsebody
public void downloadexcel(httpservletresponse res, httpservletrequest req,string name) throws exception {
       string filename = name+".xlsx";
    servletoutputstream out;
    res.setcontenttype("multipart/form-data");
    res.setcharacterencoding("utf-8");
    res.setcontenttype("text/html");
    string filepath = getclass().getresource("/template/" + filename).getpath();
    string useragent = req.getheader("user-agent");
  if (useragent.contains("msie") || useragent.contains("trident")) {
    filename = java.net.urlencoder.encode(filename, "utf-8");
  } else {
    // 非ie浏览器的处理:
         filename = new string((filename).getbytes("utf-8"), "iso-8859-1");
  }
  filepath = urldecoder.decode(filepath, "utf-8");
  res.setheader("content-disposition", "attachment;filename=" + filename);
  fileinputstream inputstream = new fileinputstream(filepath);
  out = res.getoutputstream();
  int b = 0;
  byte[] buffer = new byte[1024];
  while ((b = inputstream.read(buffer)) != -1) {
  // 4.写到输出流(out)中
  out.write(buffer, 0, b);
  }
  inputstream.close();

  if (out != null) {
  out.flush();
  out.close();
  }

}