天天看点

JAVA导出数据保存为CSV文件

1.html文件:

<form action="/prospect/downloadPhone" method="post" >
                             <div class="alert alert-warning col-lg-5" role="alert" id="alertSelect" style="display: none"><span id="dataText" style="line-height: 34px;"></span>
                                 <button type="submit" class="btn btn-info" id="download" style="float: right">导出</button>
                             </div>
                         </form>
           

2.controller层

@RequestMapping(value = "/downloadPhone",method = RequestMethod.POST)
    public void  downloadPhone(
            @RequestParam(value = "type", required = false, defaultValue = "text/plain") String type,
            HttpServletRequest request,
            HttpServletResponse response){
        try {
        	//取出session中村的手机号,或者直接数据库中查询
            List<String> phoneList=(List<String>) request.getSession().getAttribute("phoneList");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String csvFilePath = "/" +sdf.format(new Date())+".csv";
            //文件名
            String fileName = new ImportController().getFileName(csvFilePath,request);
            //文件内容
            String text = "";
            if(phoneList!=null && !phoneList.isEmpty()){
                for(String data : phoneList){
                    text+=data+"\r\n";
                }
            }
            OutputStream os = response.getOutputStream();
            BufferedOutputStream buff = new BufferedOutputStream(os);
            response.setHeader("Content-Type", type);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
            os.close();
        }catch (Exception e){
            log.error("导出短信群发手机号:{}",e.getMessage());
        }
    }