记一个导出的方法,并返回给前端文件流

记一段完整的代码

 // Controller 层

    /**
     * 导出CSV文件
     * @param
     * @return
     */
    @ApiOperation(value = "导出CSV文件")
    @PostMapping("/uploadUnitFile")
    @Log("导出CSV文件")
    public void uploadUnitFile(HttpServletResponse response,
                              @RequestBody UnitVo unitVo){
        unitService.uploadUnitFile(response, unitVo);
    }



// 接口

    /**
     * 单位导出
     * @param response
     * @param unitVo
     */
    void uploadUnitFile(HttpServletResponse response, UnitVo unitVo);




// 实现方法

  /**
     * 单位导出
     * @param response
     * @param unitVo
     */
    @Override
    public void uploadUnitFile(HttpServletResponse response, UnitVo unitVo) {
        unitVo.setPage(1);
        // 查询数据库中总共有多少条数据
        Integer count = unitMapper.selectCountNumber();
        unitVo.setPageSize(count);
        ListVo listVo = getDefectItemList(unitVo);
        List<Unit> unitList = listVo.getList();
        List resultList = new ArrayList();
        CSVPrinter printer = null;
        try {
            //格式化时间
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Object[] objects = null;
            for (Unit unit : unitList) {
                ArrayList<Object> arrayList = new ArrayList<>();
                String factoryName = factoryMapper.selectNameById(unit.getFactoryId());
                arrayList.add(factoryName);
                arrayList.add(unit.getName());
                arrayList.add(unit.getCode());
                arrayList.add(unit.getRemarks() == null ? "" : unit.getRemarks());
                arrayList.add(unit.getCreateTime());
                arrayList.add(unit.getUpdateTime());
                Integer status = unit.getStatus();
                String statusName=null;
                if(status.equals(0)){
                    statusName = "删除";
                }
                if(status.equals(1)){
                    statusName = "正常";
                }
                if(status.equals(2)){
                    statusName = "停用";
                }
                arrayList.add(statusName);
                resultList.add(arrayList);
            }
            String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
            File folder = new File(resourcePath, path);
            if(!folder.isDirectory()) folder.mkdirs();
            //截取文件扩展名
            //创建随机的文件名
            String name = UUID.randomUUID().toString() + ".csv";
            File file = new File(folder, name);
            BufferedWriter fw = new BufferedWriter (new OutputStreamWriter(
                    new FileOutputStream(file.getAbsoluteFile(),true),"gbk"));
            printer = CSVFormat.EXCEL.print(fw);
            Object[] cells = {"工厂名称", "单位名称","编号","备注","创建时间","更新时间","备注"};
            printer.printRecord(cells);
            for (int i = 0; i < resultList.size(); i++) {
                List o = (List) resultList.get(i);
                objects = o.toArray();
                printer.printRecord(objects);
                System.out.println(objects);

            }
            printer.flush();
            printer.close();
            File file1 = new File(resourcePath+'/'+path+'/'+name);
            FileInputStream fileInputStream = new FileInputStream(file1);
            response.setCharacterEncoding("GBK");
            response.setHeader("Content-Type", "application/csv");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
            OutputStream out = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public ListVo getDefectItemList(UnitVo unitVo) {
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        FactoryUser user = SecurityUtil.getFactoryUser();
        queryWrapper.ne("status",0)
                .eq("factory_id",user.getFactoryId());
        if (unitVo.getName() != null){
            queryWrapper.like("name",unitVo.getName());
        }
        Page<Unit> page = new Page<>(unitVo.getPage(),unitVo.getPageSize());
        unitMapper.selectPage(page,queryWrapper);
        ListVo listVo = new ListVo();
        listVo.setList(page.getRecords());
        listVo.setPage(unitVo.getPage());
        listVo.setTotalPages(page.getPages());
        listVo.setTotalCount(page.getTotal());
        listVo.setPageSize(unitVo.getPageSize());
        return listVo;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值