CSV导出(通过读取数据字节流直接上传文件到服务器)

文件上传服务器

文件之前读取大多数都是用前端点击相应传入后端,通过HttpServletResponse response得输入输出流进行导入导入导出数据。

近期碰到得需求是定时查询数据库数据并通过csv文件上传至系统。所以不能使用HttpServletResponse,因为对应文件流比较熟悉所以最开始使用文件流进行读写数据。

思路:将数据查出来,创建本地文件,在将数据一行一行写入,在读取本地文件获取输入流上传到服务器上后在把本地生成的文件删掉。

代码演示:

 @Override
    public void userInfo(BaseRequest<QueryUserReq> baseRequest) {
        UserDto userDto1 = new UserDto();
        List<UserDto> data = userAtom.selectByExample(userDto1);
        String[] titles = new String[]{"ID","姓名"};
        String[] propertys = new String[]{"userNo","userName"};


        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream outputStream = new DataOutputStream(stream);
        for(Object obj : data){
            //利用反射获取所有字段
            Field[] fields = obj.getClass().getDeclaredFields();
            for(String property : propertys){
                for(Field field : fields){
                    //设置字段可见性
                    field.setAccessible(true);
                    if(property.equals(field.getName())){

                        try {
                            outputStream.write(field.get(obj).toString().getBytes("gbk"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                        try {
                            outputStream.writeBytes(",");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                }
            }

            //写完一行换行
            try {
                outputStream.write("\r\n".getBytes("gbk"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Integer curDt = busiDateService.viewBusiDate().getWorkday();
        byte dataStream[] = new byte[1024];
         UploadFileReq uploadFileReq = new UploadFileReq();
            //设置文件名称
           uploadFileReq.setFileName(Constant.FILE_NAME_PREFX+curDt+ Constant.FILE_NAME_SUFFIX);

                //业务类型
                uploadFileReq.setBusiType("userInfo");
                uploadFileReq.setIsUploadOutside("1");

                uploadFileReq.setContent(stream.toByteArray());
                //上传到服务器
                Long attachId = attachService.uploadFile(uploadFileReq);
                 }

}

写入删除

 @Override
    public void userInfo(BaseRequest<QueryUserReq> baseRequest) {
        UserDto userDto1 = new UserDto();
        List<UserDto> data = userAtom.selectByExample(userDto1);
        String[] titles = new String[]{"ID","姓名"};
        String[] propertys = new String[]{"userNo","userName"};
         Integer curDt = busiDateService.viewBusiDate().getWorkday();
        //配置路径
        String localDirPath = "E:\\";

        String fileName = localDirPath+Constant.FILE_NAME_PREFX+curDt+ Constant.FILE_NAME_SUFFIX;
        try {
            ExportCsv.exportCsv(titles,propertys, data,fileName);
        } catch (IOException e) {
            e.printStackTrace();
      } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
         FileInputStream inputStream = new FileInputStream(fileName);


                inputStream.read(dataStream);
          UploadFileReq uploadFileReq = new UploadFileReq();
                uploadFileReq.setFileName(FabBankAcptConstant.FILE_NAME_PREFX+curDt+ FabBankAcptConstant.FILE_NAME_SUFFIX);

                //上传到服务器
                Long attachId = attachService.uploadFile(uploadFileReq);
           inputStream.close();

        Path path = Paths.get(fileName);
       try {
            //删除生成的文件
            boolean result = Files.deleteIfExists(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

csv导出工具类

public class ExportCsv {
    public static <T> String exportCsv(String[] titles, String[] propertys, List<T> list,String fileName) throws IOException, IllegalArgumentException, IllegalAccessException{
        File file = new File(fileName);
        //构建输出流,同时指定编码
        OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file), "gbk");

        //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号
        for(String title : titles){
            ow.write(title);
            ow.write(",");
        }
        //写完文件头后换行
        ow.write("\r\n");
        //写内容
        for(Object obj : list){
            //利用反射获取所有字段
            Field[] fields = obj.getClass().getDeclaredFields();
            for(String property : propertys){
                for(Field field : fields){
                    //设置字段可见性
                    field.setAccessible(true);
                    if(property.equals(field.getName())){
                        ow.write(field.get(obj).toString());
                        ow.write(",");
                        continue;
                    }
                }
            }
            //写完一行换行
            ow.write("\r\n");
        }
        ow.flush();
        ow.close();
        return "0";
    }
}

显然这么写多了一个没用的步骤,然后准备将查出来的数据直接转成字节流进行传递,这里要注意DataOutputStream容易出现乱码,所以使用时候一定要设置好编码例如:outputStream.write("内容".getBytes("gbk"));

 @Override
    public void userInfo(BaseRequest<QueryUserReq> baseRequest) {
        UserDto userDto = new UserDto();
        //查出对应数据
        List<UserDto> list = userAtom.selectByExample(userDto);
        ArrayList<TaskUserInfoDto> data = UserInfoTaskUtil.userInfoDtosToTaskInfo(list);
        Integer curDt = busiDateService.viewBusiDate().getWorkday();
        String[] propertys = new String[]{"appName","loginID"};

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream outputStream = new DataOutputStream(stream);
        String[] titles = new String[]{"AppName","LoginID"};
        for (int i = 0; i < titles.length; i++) {
            try {
                outputStream.write(titles[i].getBytes("gbk"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (i != titles.length-1){
                try {
                    outputStream.write("|".getBytes("gbk"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            outputStream.write(System.getProperty("line.separator").getBytes("gbk"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(Object obj : data){
            //利用反射获取所有字段
            Field[] fields = obj.getClass().getDeclaredFields();
            for(String property : propertys){
                for(Field field : fields){
                    //设置字段可见性
                    field.setAccessible(true);
                    if(property.equals(field.getName())){

                        try {
                            if (field.get(obj)!=null){
                                if (!StringUtils.isEmpty(field.get(obj).toString())){
                                    if (!field.get(obj).toString().equals("null")){
                                        outputStream.write(field.get(obj).toString().getBytes("gbk"));
                                    }
                                }

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                        try {
                            if (!property.equals("accountStatus")){
                                outputStream.writeBytes("|");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                }
            }
            //写完一行换行
            try {
                outputStream.write(System.getProperty("line.separator").getBytes("gbk"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte dataStream[] = new byte[1024];

                UploadFileReq uploadFileReq = new UploadFileReq();
            uploadFileReq.setFileName(FabBankAcptConstant.FILE_NAME_PREFX+curDt+ FabBankAcptConstant.FILE_NAME_SUFFIX);
                //业务类型
                uploadFileReq.setBusiType("userInfo");
                uploadFileReq.setIsUploadOutside("1");
                uploadFileReq.setContent(stream.toByteArray());
                Long attachId = attachService.uploadFile(uploadFileReq);
    }

 最后通过字节流便可直接上传到服务器。

猜你喜欢

转载自blog.csdn.net/weixin_52210557/article/details/127540052
今日推荐