java导出文件

导读:本篇文章讲解 java导出文件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

public void downLoad(HttpServletRequest request,HttpServletResponse response, boolean isOnLine) throws Exception {
		String fileName = "ODS报表系统指标地图.xlsx";
		//获取项目根目录
		String path2 = File.separator+"WEB-INF"+File.separator+"PICC-File.xlsx";
		InputStream path = request.getSession().getServletContext().getResourceAsStream(path2);
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
		String agent = (String) request.getHeader("USER-AGENT"); //判断浏览器类型
		try {
			if (agent != null && agent.indexOf("Firefox") != -1) {
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");//UTF-8编码,防止输出文件名乱码
			} else {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		BufferedInputStream bis = null;
		OutputStream os = null;
		response.reset();
		response.setCharacterEncoding("utf-8");
		if ("xlsx".equals(ext)) {
			response.setContentType("application/xlsx"); // xlsx格式
		} else if ("doc".equals(ext)) {
			response.setContentType("application/msword"); // word格式
		}else if (ext == "pdf") {
			response.setContentType("application/pdf"); // pdf格式
		}
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		try {
			bis = new BufferedInputStream(path);
			byte[] b = new byte[bis.available() + 1000];
			int i = 0;
			os = response.getOutputStream(); //直接下载导出
			while ((i = bis.read(b)) != -1) {
				os.write(b, 0, i);
			}
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/15921.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!