springmvc csv文件导出_csv文件下载_csv文件生成

在springmvc项目中需要导出csv文件,下载csv文件

下面介绍一下在spring中导出csv文件的实现方法,代码如下:

在controller类里添加如下方法

@RequestMapping(value = "/test/csvDownLoad", method = RequestMethod.GET)
public void csvDownLoad(ModelMap model, HttpServletRequest request,HttpServletResponse httpServletResponse) throws Exception {
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 
	String fileName = "test-";
	fileName += dateFormat.format(new Date());
	fileName += ".csv";
	
	httpServletResponse.setContentType("application/octet-stream");
	httpServletResponse.addHeader("Content-Disposition", "attachment; filename=" + fileName);
	BufferedInputStream bis = null;
	BufferedOutputStream out = null;
	String path = System.getProperty("java.io.tmpdir") + "\\tmp.csv";
	File file = new File(path);
	FileWriterWithEncoding fwwe =new FileWriterWithEncoding(file,"UTF-8");
	BufferedWriter bw = new BufferedWriter(fwwe);
	bw.write("\"abc\",\"中午\n订单\",11,123,111");
	bw.write("\n");
	bw.write("\"ab\nc\",\"aa\naa\",11,123,111");
	bw.close();
	fwwe.close();
	try {
		bis = new BufferedInputStream(new FileInputStream(file));
		out = new BufferedOutputStream(httpServletResponse.getOutputStream());
		byte[] buff = new byte[2048];
		while (true) {
		  int bytesRead;
		  if (-1 == (bytesRead = bis.read(buff, 0, buff.length))){
			  break;
		  }
		  out.write(buff, 0, bytesRead);
		}
		file.deleteOnExit();
	}
	catch (IOException e) {
		throw e;
	}
	finally{
		try {
			if(bis != null){
				bis.close();
			}
			if(out != null){
				out.flush();
				out.close();
			}
		}
		catch (IOException e) {
			throw e;
		}
	}

}

在本地请求http://localhost:8080/项目名/test/csvDownLoad 回出现下载对话框如下:

springmvc csv文件导出_csv文件下载_csv文件生成1

httpServletResponse.setContentType("application/octet-stream");//设置内容类型,这里使用的是已二进制的方式

httpServletResponse.addHeader("Content-Disposition", "attachment; filename=" + fileName);//页面出现文件下载框

System.getProperty("java.io.tmpdir")是系统临时文件目录

来源://作者:/更新时间:2015-05-15
相关文章
评论:
验证码:
匿名评论:

最新文章

文章排行