Springmvc下载Excel案例(三)

2017-10-25 19:09:11来源:CSDN作者:lovin_fang人点击

分享

接着Springmvc下载Excel案例(二)继续

上一节提到的两种不同的方式,基本上在IE上都有不兼容的问题,这里我们再来说说一种兼容两者的方式,话不多说,直接上代码

package com.action;import java.io.BufferedOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;import java.net.URLEncoder;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.util.ExcelUtil;@Controllerpublic class ExcelAction {//	@RequestMapping("/download.do")//	public ResponseEntity download(HttpServletRequest request,HttpServletResponse response) throws Exception{//		//		byte[] content = new ExcelUtil().getExcelFileByte();//		//		HttpHeaders headers = new HttpHeaders();//		if(content == null || content.length == 0){//			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//			return new ResponseEntity(null, headers, HttpStatus.OK);//		}//		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//		headers.setContentDispositionFormData("attachment",new String("测试Excel.xls".getBytes("utf-8"),"ISO-8859-1"));//		return new ResponseEntity(content, headers, HttpStatus.CREATED);//	}			@RequestMapping("/download.do")	public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{		OutputStream outputStream = null;		try{			byte[] content = new ExcelUtil().getExcelFileByte();			String fileName = "测试Excel.xls";						response.setContentType("application/octet-stream;charset=UTF-8");			String userAgent = request.getHeader("user-agent").toLowerCase();			if(userAgent != null &&((userAgent.indexOf("msie")!=-1) || (userAgent.indexOf("rv") != -1 && userAgent.indexOf("firefox") == -1))					&& ((userAgent.indexOf("msie") != -1 ||(userAgent.indexOf("rv")!=-1 && userAgent.indexOf("chrom") == -1)))){				//识别IE浏览器  				fileName = URLEncoder.encode(fileName, "UTF-8"); 			} else {  				//非IE浏览器				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  			}			response.setHeader("Content-Disposition", "attachment; filename=/"" + fileName + "/"");			response.addHeader("Content-Length", String.valueOf(content.length));			outputStream = new BufferedOutputStream(response.getOutputStream());			outputStream.write(content);			outputStream.flush();		}catch(Exception e){			response.reset();            response.setContentType("text/html;charset=UTF-8");            try {                PrintWriter writer = response.getWriter();                writer.write("<script>");                writer.write("alert('导出数据发生异常,请联系客服!');");                writer.write("</script>");                writer.close();            } catch (IOException e1) {            	e.printStackTrace();            }		}finally{			if (outputStream != null) {                try {                    outputStream.close();                } catch (IOException e) {                	e.printStackTrace();                }            }		}	}}
byte[] content = new ExcelUtil().getExcelFileByte(); 参考第一章

前端调用代码如下

<!DOCTYPE html><html>	<head>		<title>我的测试</title>		<meta http-equiv="Content-Type" content="text/html;charset=utf-8">	</head>		<body>		<a id="download1">下载excel文档</a>		<br>		<a id="download2">下载Excel文档2</a>	</body>	<script type="text/javascript" src="../js/jquery.min.js"></script>	<script type="text/javascript">		$("#download1").click(function(){			var contextHref = getContextPath();			window.location.href = contextHref+"/download.do";		});				function getContextPath(){      		    var pathName = document.location.pathname;     		    var index = pathName.substr(1).indexOf("/");     		    var contextRoot = pathName.substr(0,index+1);		    var port = window.location.port;		    return "http://localhost:"+port+contextRoot;		} 				$("#download2").click(function(){			var contextHref = getContextPath();			var url = contextHref+"/download.do";			window.open(url, "_blank");		});			</script></html>

测试在IE和google上通过


以上解决方案,虽不是最好的解决方案,在网上大家也都能搜索到,希望对初学者有用,自己也当做一个笔记。如果有其他的解决方案,希望大家指点指点


另外给一些SpringExcel下载的URL给大家做参考

http://blog.csdn.net/qiubabin/article/details/50113675

http://blog.csdn.net/java_wisely/article/details/9765555

http://www.cnblogs.com/blog5277/p/6065601.html




最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台