JAVA导出数据保存为CSV文件

1.html文件:

  

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 phoneList=(List) 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());
        }
    }

你可能感兴趣的:(Java)