在浏览器输入请求http://ip:port/excel/down.html ,下载服务端文件
package com.harara.easyexcel.controller; import com.alibaba.excel.ExcelWriter;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; /** * 下载文件 demo * @author : harara * @version : 2.0 * @date : 2020/6/11 9:44 */ @RequestMapping("/excel") @RestController public class ExcelController { /** * 下载已经生成好的文件 * @param request * @param response */ @GetMapping("/down.html") public void download1Excel(HttpServletRequest request, HttpServletResponse response){ OutputStream out = null; ExcelWriter excelWriter = null; File file = null; FileInputStream input = null; try { out = response.getOutputStream(); //设置ConetentType CharacterEncoding Header,需要在out.write()之前设置 response.setContentType("mutipart/form-data"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition","attachment;filename=excelByModel.xlsx"); //本地已存在的文件 file = new File("excelByModel.xlsx"); input = new FileInputStream(file); int len; byte[] bytes = new byte[1024]; while((len =input.read(bytes))> 0){ out.write(bytes,0,len); } out.flush(); }catch (Exception e){ e.printStackTrace(); }finally { try { input.close(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); }catch (Exception e){ e.printStackTrace(); } } } }