Java Web 导出Excel 之路径选择

我主要说明的是   在数据都填到单元格后,下来进行文件输出时 ,需要做的事

主要代码为

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();
	     }
 
  
 
 

你可能感兴趣的:(JAVA)