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 回出现下载对话框如下:

httpServletResponse.setContentType("application/octet-stream");//设置内容类型,这里使用的是已二进制的方式
httpServletResponse.addHeader("Content-Disposition", "attachment; filename=" + fileName);//页面出现文件下载框
System.getProperty("java.io.tmpdir")是系统临时文件目录
来源://作者:/更新时间:2015-05-15
顶
踩
相关文章:
- springmvc 后台参数校验 使用用注解方式及国际化的写
- springmvc controller跳转到下一个controller,action
- springmvc controller返回字符串乱码
- springmvc项目进行junit测试方法
- springmvc 文件上传报错org.springframework.web.util
- springmvc 在controller类中如何读取.properties变量
- 使用eclipse 运行springmvc官方实例spring-mvc-showca
- springmvc 使用注解参数传递格式化日期和数字
- springmvc 传递和接收数组参数
- springmvc 表单提交时间字段_springMVC form提交404
