将数据下载导出为csv文件

  • Post author:
  • Post category:其他


/**

* 数据保存为csv文件

* @param pdjgDTO

* @param response

* @param errors

*/

@PostMapping(value = “/pdjgbc”)

public void pdjgbc(@Valid @RequestBody PdjgDTO pdjgDTO, HttpServletResponse response, Errors errors) throws IOException {


// 服务端数据校验

if (errors.hasErrors()) {


throw new ValidationException(errors);

}

            //根据开始时间,查出判定结果
            OnlineExpertRes onlineExpertRes = onlineExpertResService.getByStartTime(pdjgDTO.getTime());

            // 根据表名online_expert_res,获取表中的所有字段名:
            List<FieldVO> fieldVOS = onlineExpertResService.getFieldByTable("online_expert_res");

            List<String> head = new ArrayList<>();
            List<List<String>> datas = new ArrayList<>();

            // 将判定结果中的所有字段,添加到csv文件的head中
            for (FieldVO fieldVO : fieldVOS) {
                String cname = fieldVO.getColumnName();
                System.out.println("--cname==" + cname);
                if (cname.length() == 0 || cname.equals("id") || cname.equals("operator") || cname.equals("create_time") || cname.equals("type")) {
                    continue;
                }
                String comment = fieldVO.getColumnComment();
                comment = comment.replaceAll("\r|\n", "");
                head.add(comment);
            }

            // 将查询出的判定结果数据,添加到csv文件的datas中
            try {
                Field[] field = OnlineExpertRes.class.getDeclaredFields();

                List<String> list = new ArrayList<>();
                for (FieldVO fieldVO : fieldVOS) {
                    String filedName = fieldVO.getColumnName();
                    String vx = "";
                    for (Field f : field) {
                        Column column = f.getAnnotation(Column.class);
                        String fname = f.getName();
                        if (column != null) {
                            fname = column.name();
                        }
                        if (fname.equals("id") || fname.equals("operator") || fname.equals("create_time") || fname.equals("type")) {
                            continue;
                        }
                        if (filedName.equals(fname)) {
                            f.setAccessible(true);
                            if (f.get(onlineExpertRes) != null) {
                                if (fname.equals("date")) {
                                    Date date = (Date) f.get(onlineExpertRes);
                                    vx = DateFormatUtils.format(date, "yyyy-MM-dd");
                                } else {
                                    vx = f.get(onlineExpertRes).toString();
                                }
                            }

                            list.add(vx);

                        } else {

                        }
                    }
                    if (vx == "") {
                        System.out.println("filedName==" + filedName);
                    }
                }
                datas.add(list);

            } catch (Exception e) {
                e.printStackTrace();
            }


            //创建csv文件,下载

            String filePath = "";
            String basePath = "";
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().startsWith("win")) {
                basePath = properties.getFilePaths().getTemp() + System.getProperty("file.separator");
            } else {
                basePath = properties.getFilePaths().getTemp() + System.getProperty("file.separator");
            }
            String fileid = UUID.randomUUID().toString();

            File file = CsvUtil.createCSVFile(head, datas, basePath, fileid);
            filePath = basePath + fileid + ".csv";

// File file =new File(filePath);

System.out.println(“—filePath=” + filePath);

// 如果文件名存在,则进行下载

if (file.exists()) {


String fileName = fileid;

// 配置文件下载

response.setHeader(“content-type”, “application/octet-stream”);

response.setContentType(“application/octet-stream”);

// 下载文件能正常显示中文

                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download successfully!");
                } catch (Exception e) {
                    System.out.println("Download failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
           
    }



版权声明:本文为weixin_45109925原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。