首页 > 编程语言 > 详细

java导出csv文件=js+controller

时间:2015-12-08 02:18:17      阅读:285      评论:0      收藏:0      [点我收藏+]

/**

*js层

*/

downLoad = function(){

var params = {

"value" : $("#id").val()

};

window.open("/down/downLoad?value="+$("#id").val());//不可以使用ajax请求,因为流无法传输到前端,需要另打开界面。路径+传输到controller的值

};

/**

*controller层

*/

@RequestMapping(value = "/downLoad", method=RequestMethod.POST,produces="text/html;charset=UTF-8" )

public ModelAndView downLoad(int value) throws Exception {

List<String> downList = new ArrayList<String>();

List<String> headList = new ArrayList<String>();

HttpServletResponse response = getResponse();

response.reset(); ?

response.setCharacterEncoding("UTF-8");

response.setContentType("application/octet-stream");

//String downloadFileName =new String("下载".getBytes("utf-8"),"iso-8859-1");//一般是utf-8但是ie下载时,文件名会乱码

String downloadFileName =new String("下载".getBytes("gb2312"),"iso-8859-1");//IE11下文件名不会乱码

// downloadFileName += new String(bi.getBatchName().getBytes("utf-8"),"iso-8859-1")+"-";

downloadFileName += new String(bi.getBatchName().getBytes("gb2312"),"iso-8859-1")+"-";

downloadFileName += new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//在文件名中加入下载的年月日时分秒

response.setHeader("Content-Disposition", "attachment; filename=\""+ downloadFileName + ".csv\"");

ServletOutputStream sos = response.getOutputStream();

boolean isSuccess=CsvUtils.exportCsv(sos ,headList,downList);

return null;//不需要返回前端任何内容

}

/**

*exportCsv方法

*/

? ?public static boolean exportCsv(ServletOutputStream outputStream,List<String> headList, List<String> dataList){

? ? ? ?boolean isSucess=false;

? ? ? ?try {

? ? ? ? ? ?StringBuilder sb = new StringBuilder();

? ? ? ? ? ?if(headList!=null && !headList.isEmpty()){

? ? ? ? ? ? ? ?for(String data : headList){

? ? ? ? ? ? ? ? sb.append(data);

? ? ? ? ? ? ? ? sb.append("\r");//在这里需要将数据一行一行展示

? ? ? ? ? ? ? ?}

? ? ? ? ? ?}

? ? ? ? ? ?if(dataList!=null && !dataList.isEmpty()){

? ? ? ? ? ? ? ?for(String data : dataList){

? ? ? ? ? ? ? ? sb.append(data);

? ? ? ? ? ? ? ? sb.append("\r");

? ? ? ? ? ? ? ?}

? ? ? ? ? ?}

? ? ? ? ? ?outputStream.write(sb.toString().getBytes("GBK"));//写入输出流

? ? ? ? ? ?outputStream.flush();//缓存流

? ? ? ? ? ?isSucess=true;

? ? ? ?} catch (Exception e) {

? ? ? ? e.printStackTrace();

? ? ? ? ? ?isSucess=false;

? ? ? ?}finally{

? ? ? ? if(outputStream!=null){

? ? ? ? try {

? ? ? ? outputStream.close();//一定要将流关闭,否则日志中会出错

? ? ? ? ? ? ? ? outputStream=null;

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? }?

? ? ? ? }

? ? ? ?}

? ? ? ?return isSucess;

?

? ?}

java导出csv文件=js+controller

原文:http://774640787.iteye.com/blog/2262350

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!