实现java导出功能

controller

@GetMapping("/export")
    public void export(HttpServletResponse response, Entity entity) {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //水平左对齐,垂直中间对齐
        writer.getStyleSet().setAlign(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        ServletOutputStream out = null;
        try {
            entityService.export(writer, entity);
            //自定义标题别名
            //设置响应头
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()) + "-数据" + ".xlsx"
                    //设置响应头
                    , "utf-8"));
            out = response.getOutputStream();
            writer.flush(out, true); 
        } catch (Exception e) {
            log.error("export error: ", e);
        } finally {
            // 关闭writer,释放内存
            writer.close();
            IoUtil.close(out);
        }
    }

service

void export(ExcelWriter writer, Entity entity);

serviceImpl

@Override
    public void export(ExcelWriter writer, Entity entity) {
        List<Map<String, Object>> exportData = new ArrayList<>();
        List<Entity> formDataList = entitymapper.findAll(entity);//获取数据
        for (int i=0;i<formDataList.size();i++){
            Map<String, Object> dataDetail = new LinkedHashMap<>(formDataList.size() + 2);
            dataDetail.put("序号", i+1);
            dataDetail.put("姓名",formDataList.get(i).getName());
            dataDetail.put("联系电话",formDataList.get(i).getMobile());
            dataDetail.put("身份证号",formDataList.get(i).getIdnumber());
            dataDetail.put("内容",formDataList.get(i).getContent());
            dataDetail.put("创建时间",formDataList.get(i).getCreatetime());
            exportData.add(dataDetail);
        }
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 100);
        writer.setColumnWidth(5, 30);
        writer.write(exportData);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WAZYY0619

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值