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());
}
到这里就结束了,简单,方便。