Java Controller層下載指定Excel模板
/** * 下載模板 * @param request * @param response */ @RequestMapping(value="template") public void template(HttpServletRequest request,HttpServletResponse response ){ try {
//指定需要下載的檔案路徑 String downLoadPath ="E:"+File.separator+"upload"+File.separator+"template"+File.separator+"file_template.xlsx"; String fileName=downLoadPath.substring(downLoadPath.lastIndexOf("/")+1); byte[] buffer=null; buffer = downFileByte(downLoadPath) ; String fileSuffixName= fileName.substring(fileName.lastIndexOf(".")+1); response.reset(); //清除快取 response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //設定字符集和檔案字尾名 String name="歷史專案模板"; name = new String(name.getBytes(), "ISO-8859-1"); response.setHeader("Content-Disposition","attachment; filename=" +name+"."+fileSuffixName); // 設定檔名稱 OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (Exception e) { e.printStackTrace(); Log4jUtil.getLog4jUtil().error("下載模板"+e.getMessage()); } }
/** * 下載檔案 * 返回byte[] * @param fileName 需要下載的檔名 * @return * @throws Exception */ public static byte[] downFileByte(String downLoadPath) throws Exception{ byte[] return_arraybyte=null; InputStream ins=new FileInputStream(downLoadPath ); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bufsize = 0; while ((bufsize = ins.read(buf, 0, buf.length)) != -1) { byteOut.write(buf, 0, bufsize); } return_arraybyte = byteOut.toByteArray(); byteOut.close(); ins.close(); return return_arraybyte; }
注意:1.返回值一定要是void;2.如果下載檔名稱中文亂碼了,建議用時間戳命名.