【JAVA下载excel工具类】

SpringBoot 整合java下载excel

前几天逛吧的时候发现了一个很好的下载功能,代码非常的少,推荐使用。
下面我们就来看看吧

  • 导入maven仓库
        <dependency>
            <groupId>com.github.liaochong</groupId>
            <artifactId>myexcel</artifactId>
            <version>3.3.0.GA</version>
        </dependency>
  • 创建excel下载工具类
package com.hjy.mall.common.util;


import com.github.liaochong.myexcel.core.DefaultStreamExcelBuilder;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;
import com.hjy.mall.common.api.ResultCode;
import com.hjy.mall.common.exception.ApiException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;

public class StreamExport {

    /**导出表格最大容量*/
    public static final Integer EXCEL_MAX_CAPACITY = 60_000;

    public static void flowPattern(HttpServletResponse response, Class clazz, List list, String fileName) {
        //long start = System.currentTimeMillis();
        try (DefaultStreamExcelBuilder streamExcelBuilder = DefaultStreamExcelBuilder
                .of(clazz)
                .threadPool(Executors.newFixedThreadPool(10))
                .capacity(EXCEL_MAX_CAPACITY)
                .start()) {
            // 多线程异步获取数据并追加至excel,join等待线程执行完成
            List<CompletableFuture> futures = new ArrayList<>();

                CompletableFuture future = CompletableFuture.runAsync(() -> {
                    List dataList = list;
                    // 数据追加
                    streamExcelBuilder.append(dataList);
                });

                futures.add(future);
            futures.forEach(CompletableFuture::join);
            // 最终构建
            Path zip = streamExcelBuilder.buildAsZip(fileName);
            AttachmentExportUtil.export(zip,fileName+".zip",response);
        } catch (IOException e) {
            // e.printStackTrace();
           throw new ApiException(ResultCode.FAILED);
        }

    }
}
  • 编写接口示范
    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('/finance/financeExcel')")
    public void financeExcel(){
    //用户列表
     List<UserDto> userList= UserService.getUserInfo();
     //调用工具类
     StreamExport.flowPattern(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse(), UserDto.class,userList , "用户列表"+ DateFormatter.HHmmssSSS());
    }

到这里就结束了,简单,方便。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值