欢迎访问设·集合!

设·集合

您现在的位置是:首页 > 办公软件 > Excel

如何优雅的导出Excel

设·集合小编 发布时间:2023-03-03 09:20:50 535次最后更新:2024-03-08 10:51:16

前言

公司项目最近有一个需要:报表导出。整个系统下来,起码超过一百张报表需要导出。这个时候如何优雅的实现报表导出,释放生产力就显得很重要了。下面主要给大家分享一下该工具类的使用方法与实现思路。

实现的功能点

对于每个报表都相同的操作,我们很自然的会抽离出来,这个很简单。而最重要的是:如何把那些每个报表不相同的操作进行良好的封装,尽可能的提高复用性;针对以上的原则,主要实现了一下关键功能点:

  • 导出任意类型的数据
  • 自由设置表头
  • 自由设置字段的导出格式

使用实例

上面说到了本工具类实现了三个功能点,自然在使用的时候设置好这三个要点即可:

  • 设置数据列表
  • 设置表头
  • 设置字段格式

下面的export函数可以直接向客户端返回一个excel数据,其中productInfoPos为待导出的数据列表,ExcelHeaderInfo用来保存表头信息,包括表头名称,表头的首列,尾列,首行,尾行。因为默认导出的数据格式都是字符串型,所以还需要一个Map参数用来指定某个字段的格式化类型(例如数字类型,小数类型、日期类型)。这里大家知道个大概怎么使用就好了,下面会对这些参数进行详细解释。

@Override
    public void export(HttpServletResponse response, String fileName) {
        // 待导出数据         List<TtlProductInfoPo> productInfoPos = this.multiThreadListProduct();
        ExcelUtils excelUtils = new ExcelUtils(productInfoPos, getHeaderInfo(), getFormatInfo());
        excelUtils.sendHttpResponse(response, fileName, excelUtils.getWorkbook());
    }

    // 获取表头信息     private List<ExcelHeaderInfo> getHeaderInfo() {
        return Arrays.asList(
                new ExcelHeaderInfo(1, 1, 0, 0, `id`),
                new ExcelHeaderInfo(1, 1, 1, 1, `商品名称`),

                new ExcelHeaderInfo(0, 0, 2, 3, `分类`),
                new ExcelHeaderInfo(1, 1, 2, 2, `类型ID`),
                new ExcelHeaderInfo(1, 1, 3, 3, `分类名称`),

                new ExcelHeaderInfo(0, 0, 4, 5, `品牌`),
                new ExcelHeaderInfo(1, 1, 4, 4, `品牌ID`),
                new ExcelHeaderInfo(1, 1, 5, 5, `品牌名称`),

                new ExcelHeaderInfo(0, 0, 6, 7, `商店`),
                new ExcelHeaderInfo(1, 1, 6, 6, `商店ID`),
                new ExcelHeaderInfo(1, 1, 7, 7, `商店名称`),

                new ExcelHeaderInfo(1, 1, 8, 8, `价格`),
                new ExcelHeaderInfo(1, 1, 9, 9, `库存`),
                new ExcelHeaderInfo(1, 1, 10, 10, `销量`),
                new ExcelHeaderInfo(1, 1, 11, 11, `插入时间`),
                new ExcelHeaderInfo(1, 1, 12, 12, `更新时间`),
                new ExcelHeaderInfo(1, 1, 13, 13, `记录是否已经删除`)
        );
    }

    // 获取格式化信息     private Map<String, ExcelFormat> getFormatInfo() {
        Map<String, ExcelFormat> format = new HashMap<>();
        format.put(`id`, ExcelFormat.FORMAT_INTEGER);
        format.put(`categoryId`, ExcelFormat.FORMAT_INTEGER);
        format.put(`branchId`, ExcelFormat.FORMAT_INTEGER);
        format.put(`shopId`, ExcelFormat.FORMAT_INTEGER);
        format.put(`price`, ExcelFormat.FORMAT_DOUBLE);
        format.put(`stock`, ExcelFormat.FORMAT_INTEGER);
        format.put(`salesNum`, ExcelFormat.FORMAT_INTEGER);
        format.put(`isDel`, ExcelFormat.FORMAT_INTEGER);
        return format;
    }

实现效果

转自:如何优雅的导出Excel - 掘金

广告位

热心评论

评论列表