Java Web 匯出Excel 之路徑選擇
阿新 • • 發佈:2019-01-27
我主要說明的是 在資料都填到單元格後,下來進行檔案輸出時 ,需要做的事
主要程式碼為
String fileName = request.getParameter("fileName");//獲取傳過來的檔名,該檔名是你匯出excel的檔名 if(null==fileName){ String url = request.getRequestURL().toString(); fileName = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".")>-1?url.lastIndexOf("."):url.length()); fileName += UUID.randomUUID(); } try { response.reset(); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type","application/force-download"); response.setHeader("Content-Type","application/vnd.ms-excel"); final String userAgent = request.getHeader("USER-AGENT");//獲取你瀏覽器的代理 //下面主要是讓檔名適應不同瀏覽器的編碼格式 try { String finalFileName = null; if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器 finalFileName = URLEncoder.encode(fileName,"UTF8"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器 finalFileName = new String(fileName.getBytes(), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(fileName,"UTF8");//其他瀏覽器 } response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//這裡設定一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中開啟 } catch (UnsupportedEncodingException e) { } OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); }