欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据导出excel等格式文件

程序员文章站 2022-03-31 16:58:39
...
@ApiOperation(value = "导出到excel")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "data", dataType = "String", required = true,
                    value = "name=必填,名称;tp=必填,excel/csv",
                    defaultValue = "{\"ids\":\"1,2\",\"tp\":\"excel\"}")
    })
    @GetMapping("/export")
    public void export(String data) throws IOException {
        String ids = JSON.parseObject(data).getString("ids");
        String tp = JSON.parseObject(data).getString("tp");
        if (StringUtils.isEmpty(ids)) {
            throw new SquirrelRuntimeException(RespConst.NULL, "ids参数为空");
        }
        String[] idArr = ids.split(",");
        List<DataSupplier> list = new ArrayList<>();
        for (String id : idArr) {
            DataSupplier dataSupplier = new DataSupplier();
            dataSupplier.setId(Integer.valueOf(id));
            list.add(dataSupplier);
        }
        List<Integer> lists = new ArrayList<>();
        for (DataSupplier dataSupplier : list) {
            lists.add(dataSupplier.getId());
        }
        List<DataSupplier> page = dataSupplierService.findAllById(lists);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String fileName = "格式_"+ new Date().getTime() + "";
        if (StringUtils.equalsIgnoreCase(tp, "excel")) {
            writeWithHead(page, baos);
            fileName = fileName + ExcelTypeEnum.XLSX.getValue();
        } else {
//            toCsv(page, baos);
            baos.write(JSON.toJSONString(page).getBytes());
            fileName = fileName + ".txt";
        }
        // 获取文件名称,中文可能被URL编码
        fileName = URLDecoder.decode(fileName, "UTF-8");
        byte[] bytes = baos.toByteArray();

        /*
         * 构造响应的头
         */
        HttpHeaders headers = new HttpHeaders();
        // 下载之后需要在请求头中放置文件名,该文件名按照ISO_8859_1编码。
        String filenames = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=" + filenames);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        OutputStream output = response.getOutputStream();
        output.write(bytes);
        output.flush();
        output.close();
    }


    public ByteArrayOutputStream writeWithHead(List<DataSupplier> dList, ByteArrayOutputStream baos) throws IOException {
        Sheet sheet1 = new Sheet(1, 0);
        sheet1.setSheetName("sheet1");
        ExcelWriter writer = new ExcelWriter(baos, ExcelTypeEnum.XLSX);

        List<List<String>> data = new ArrayList<>();
        for (DataSupplier provider : dList) {
            List<String> item = new ArrayList<>();
            item.add(provider.getId() + "");
            item.add(provider.getName());
            item.add(provider.getCode());
            item.add(provider.getSupplyStart() + "");
            item.add(provider.getSupplyEnd() + "");
            item.add(provider.getSignType());
            item.add(provider.getSignDate() + "");
            item.add(provider.getStatus());
            item.add(provider.getStopDate() + "");
            data.add(item);
        }
        List<List<String>> head = new ArrayList<List<String>>();
        List<String> headCoulumn1 = new ArrayList<String>();
        List<String> headCoulumn2 = new ArrayList<String>();


        headCoulumn1.add("id");
        headCoulumn2.add("名称");

        head.add(headCoulumn1);
        head.add(headCoulumn2);


        Table table = new Table(1);
        table.setHead(head);
        writer.write0(data, sheet1, table);
        writer.finish();
        return baos;
    }

    /**
     * @param list
     * @param baos
     * @throws IOException
     */
    private void toCsv(List<DataSupplier> list, ByteArrayOutputStream baos) throws IOException {
//        CsvWriter csvWriter = new CsvWriter(baos, ',', StandardCharsets.UTF_8);
        CsvWriter csvWriter = new CsvWriter(baos, ',', Charset.forName("GBK"));
        //写header
        String[] header = {"id", "名称"};
        csvWriter.writeRecord(header);

        //写内容
        for (DataSupplier item : list) {
            String[] content = {item.getId() + "",
                    item.getName(), item.getCode(), DatetimeUtil.format(item.getSupplyStart(), DatetimeUtil.YYYY_MM_DD_HH_MM_SS),
                    DatetimeUtil.format(item.getSupplyEnd()};

            csvWriter.writeRecord(content);
        }
        csvWriter.close();
    }