csv下载功能学习记录(原地址找不到了)

2020-01-17  本文已影响0人  在一年四季的风中凌乱

依赖引入

        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>

csv内容写入和浏览器实现下载

    @ApiOperation("根据条件汇总订单并下载excel")
    @GetMapping("export")
    @ResponseBody
    @ApiPageable
    public void exportOrderCSV(@QuerydslPredicate(root = PurchaseOrderView.class) Predicate predicate,
                               @ApiParam("文本搜索条件。") @RequestParam(value = "searchText", required = false) String searchText,
                               @ApiParam("创建时间查询 开始 ISO 8601时间格式") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam(value = "startTime", required = false) ZonedDateTime startTime,
                               @ApiParam("创建时间查询 结束 ISO 8601时间格式") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam(value = "endTime", required = false) ZonedDateTime endTime,
                               @ApiIgnore Pageable pageable, HttpServletResponse response) throws IOException {

        Iterable<PurchaseOrderView> purchaseOrderViewIterable = purchaseOrderService.getPurchaseOrderByParam(predicate, searchText,
                startTime, endTime, pageable);
        ServletOutputStream outputStream = response.getOutputStream();
        //csv工作空间
        CsvWriter csvWriter = new CsvWriter(outputStream, ',', Charset.forName("gb2312"));
        //设置表头
        String[] headers = {"序号","订单ID", "合同号"};
        csvWriter.writeRecord(headers);
        //设置行号
        int index = 0;
        //对数据进行遍历
        for (PurchaseOrderView purchaseOrderView : purchaseOrderViewIterable) {
            //拼接数据
            String orderId = String.valueOf(purchaseOrderView.getId());
            String conNo = purchaseOrderView.getContractNo();
            //拼接行数据
            String[] writeArr = {String.valueOf(index + 1), orderId, conNo.replaceAll("[(|)]", "")};
            try {
                //将数据写入csv
                csvWriter.writeRecord(writeArr);
            } catch (IOException e) {
                e.printStackTrace();
            }
            index++;
        }
        //文件名
        String fileName = new String("税务信息汇总表.csv".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment; filename=" + fileName);
        csvWriter.flush();
        csvWriter.close();
        response.flushBuffer();

    }
上一篇下一篇

猜你喜欢

热点阅读