springmvc特有下载文件的方式

2018-07-21  本文已影响0人  马木木
@RequestMapping("downloadCSV.htm")
    public ResponseEntity<byte[]> downloadCSV(RequestEntity entity){
        String fileName="权限报表.csv";
//        将页数置为0表示部分页 sql有处理<#if>
        String[] headers={"工号","姓名","部门","职位","角色","状态","创建时间","更新时间"};
        entity.setLimit(0);
        ByteArrayOutputStream bout;
        HttpHeaders httpHeaders=new HttpHeaders();
        try {
            List<EyeUser> userList=smartEyeUserService.getUserList(entity);

            bout=processData(userList,headers);

            String downloadFileName=new String((fileName + DateUtil.format(new Date(), "yyyyMMddHHmmss"))
                    .getBytes("GB2312"), "ISO8859-1") + ".csv" ;
            httpHeaders.setContentDispositionFormData("attachment",downloadFileName);
//            二进制下载
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(bout.toByteArray(),httpHeaders,HttpStatus.CREATED);

        } catch (IOException e) {
            logger.error("人员列表下载出错",e);
            String message=e.getMessage();
            httpHeaders.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<byte[]>(message.getBytes(),httpHeaders,HttpStatus.METHOD_FAILURE);


        }

    }
/**
     * 处理下载数据
     * @param userList
     * @param headers
     * @return
     */
    private ByteArrayOutputStream processData(List<EyeUser> userList, String[] headers) throws IOException {

        ByteArrayOutputStream bout=new ByteArrayOutputStream();
        CsvWriter csvWriter=new CsvWriter(bout,',',Charset.forName("GBK"));
        csvWriter.writeRecord(headers);
        for(EyeUser user:userList){
            if(user==null){
                continue;
            }
            csvWriter.writeRecord(getDataArray(user));
        }
        csvWriter.close();
        return bout;
    }

    private String[] getDataArray(EyeUser user) {
        return new String[]{user.getUserId(),user.getUserName(),user.getUserDept(),user.getUserPosition(),user.getRoleName(),user.getState()==1?"有效":"无效",user.getCreateTime(),user.getUpdateTime()};
    }
上一篇下一篇

猜你喜欢

热点阅读