最近项目内有需要导出多个excel自动合并zip压缩包,趁摸鱼之际,记录下造的轮子。
使用CompletableFuture将任务拆分导出再合并返回给客户端,提高导出效率。话不多说,show you the code!
引入依赖
<dependency>
<groupId>cn.idev.excel</groupId>
<artifactId>fastexcel</artifactId>
<version>1.2.0</version>
</dependency>工具代码
package com.hzj.labor.util;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;
import cn.idev.excel.write.builder.ExcelWriterBuilder;
import cn.idev.excel.write.metadata.WriteSheet;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
@UtilityClass
public class ExcelZipUtil {
private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), ThreadFactoryBuilder.create().setNamePrefix("excel-export-").build());
private File getTemplateFile(String templatePath) {
if (StringUtils.isBlank(templatePath)) {
return null;
}
try {
Resource resource = new ClassPathResource(templatePath);
if (resource.exists()) {
return resource.getFile();
}
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public <T> void exportZip(String zipFilename, String templatePath, List<ExcelData<T>> excelDataList, HttpServletResponse response) {
if (CollectionUtils.isEmpty(excelDataList)) {
throw new RuntimeException("导出数据为空!");
}
File templateFile;
if (StringUtils.isNotBlank(templatePath)) {
templateFile = getTemplateFile(templatePath);
if (templateFile == null) {
throw new RuntimeException("模板文件不存在!");
}
} else {
templateFile = null;
}
if (StringUtils.isBlank(zipFilename)) {
zipFilename = "export.zip";
} else if (!zipFilename.toLowerCase(Locale.ROOT).endsWith(".zip")) {
zipFilename += ".zip";
}
// 根据实际的文件类型找到对应的 contentType
String contentType = MediaTypeFactory.getMediaType(zipFilename).map(MediaType::toString).orElse("application/zip");
response.setContentType(contentType);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(zipFilename, StandardCharsets.UTF_8));
try {
// 并行生成所有Excel文件
List<CompletableFuture<ExcelFileData>> futures = excelDataList.stream()
.map(excelData -> CompletableFuture.supplyAsync(() -> generateExcelBytes(excelData, templateFile), executor)
.exceptionally(e -> {
throw new RuntimeException(e);
}))
.toList();
List<ExcelFileData> excelFiles = futures.stream()
.map(CompletableFuture::join)
.toList();
// 统一写入ZIP
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
for (ExcelFileData fileData : excelFiles) {
zipOut.putNextEntry(new ZipEntry(fileData.getFilename()));
zipOut.write(fileData.getBytes());
zipOut.closeEntry();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("导出zip文件成功,文件名:{}", zipFilename);
}
/**
* 生成单个Excel文件字节数组
*/
private <T> ExcelFileData generateExcelBytes(ExcelData<T> excelData, File templateFile) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
ExcelWriterBuilder builder = FastExcel.write(outputStream)
.autoCloseStream(false)
.registerConverter(new ExcelBigNumberConvert());
if (null != templateFile) {
builder.withTemplate(templateFile);
}
ExcelWriter excelWriter = builder.build();
WriteSheet sheet = FastExcel.writerSheet().build();
if (null != templateFile) {
// 写入模板数据
excelWriter.fill(excelData.getData(), sheet);
} else {
// 写入普通数据
excelWriter.write(List.of(excelData.getData()), sheet);
}
// 必须先完成Excel写入,才能获取完整的字节数组
excelWriter.finish();
log.info("生成Excel文件成功,文件名:{}", excelData.getFilename());
return new ExcelFileData(excelData.getFilename(), outputStream.toByteArray());
} catch (IOException e) {
throw new RuntimeException("生成Excel文件失败:" + excelData.getFilename(), e);
}
}
/**
* Excel文件数据容器
*/
@Getter
private class ExcelFileData {
private final String filename;
private final byte[] bytes;
public ExcelFileData(String filename, byte[] bytes) {
this.filename = filename;
this.bytes = bytes;
}
}
/**
* Excel 数值长度位15位 大于15位的数值转换位字符串
*/
public class ExcelBigNumberConvert implements Converter<Long> {
@Override
public Class<Long> supportJavaTypeKey() {
return Long.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
Object data = cellData.getData();
if (data == null) {
return null;
}
String s = String.valueOf(data);
if (s.matches("^\\d+$")) {
return Long.parseLong(s);
}
return null;
}
@Override
public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (object != null) {
String str = object.toString();
if (str.length() > 15) {
return new WriteCellData<>(str);
}
}
WriteCellData<Object> cellData = new WriteCellData<>(new BigDecimal(object));
cellData.setType(CellDataTypeEnum.NUMBER);
return cellData;
}
}
/**
* sheet数据
*/
@Setter
@Getter
public static class ExcelData<T> {
private T data;
private String filename;
public ExcelData(T data, String filename) {
this.data = data;
this.filename = filename;
}
}
}使用
@Override
public void generatePrintExcelZip(List<Long> ids, HttpServletResponse resp) {
// 校验ids是否为空
Assert.isTrue(CollectionUtils.isNotEmpty(ids), "ids不能为空");
List<LabPreWorkMeetingEntity> exportList = listByIds(ids);
Assert.notEmpty(exportList, "导出数据为空");
// 生成Excel文件
List<ExcelZipUtil.ExcelData<LabPreWorkMeetingPrintVO>> voList = exportList.stream()
.map(this::convertToExcelVO)
.toList();
// 压缩并下载
ExcelZipUtil.exportZip(String.format("导出%s.zip", DateUtil.today()), "templates/meeting-print.xlsx", voList, resp);
}
private ExcelZipUtil.ExcelData<LabPreWorkMeetingPrintVO> convertToExcelVO(LabPreWorkMeetingEntity entity) {
LabPreWorkMeetingPrintVO vo = BeanUtil.copyProperties(entity, LabPreWorkMeetingPrintVO.class);
if (entity.getMeetingTime() != null) {
vo.setMeetingTime(DateUtil.formatLocalDateTime(entity.getMeetingTime()));
}
vo.setPrintTime(DateUtil.now());
return new ExcelZipUtil.ExcelData<>(vo, entity.getMeetingName()+".xlsx");
}结语
可优化点还有很多,比如多模板,多sheet等,以后需要再修改吧。牛马不易,摸鱼续命
凡是过往,皆为序章!
https://rentry.co/pkufkw3h
Mounjaro weight loss
credit karma alternative
News129.online is an online resource for readers offering readers access to informative content, useful insights, and noteworthy stories. The website brings together fresh publications covering noteworthy developments, useful topics, practical information, and subjects that may interest a wide audience.
The platform serves readers who want to broaden their knowledge, discover interesting topics, and keep track of relevant developments. The website can be visited at https://www.news129.online. The publication focuses on presenting information in an accessible and reader-friendly format, with new materials expanding the website over time.
diploma mill
Podrobnosti o akci: odvoz pohovky praha
Potřebujete pohyb? Vyklízení Praha pohodlné řešení pro rezidenční, soukromé a komerční stěhování. Zakázka přepravy nábytku, balení majetku, odvoz těžkých předmětů a montáž nábytku. Vyberte si vhodnou škálu služeb s ohledem na vaše úkoly.
Сувениры с логотипом https://korporativnye-podarki-buy.ru в Санкт-Петербурге — эффективный инструмент корпоративного маркетинга и формирования имиджа компании. Выбирайте бизнес-подарки, промопродукцию, брендированную канцелярию, текстиль и аксессуары для сотрудников, клиентов и деловых партнёров.
известный Telegram-бот глаз бога онлайн связанный с поиском информации по различным исходным данным. Разберитесь, как устроен сервис, какие функции ему приписывают, какие ограничения существуют и почему важно соблюдать правила защиты персональных данных.
Ищете, где купить https://keramicheskaya-plitka-msk.ru керамическую плитку в Москве? Ознакомьтесь с ассортиментом настенной и напольной плитки, современными коллекциями, популярными дизайнами и вариантами отделки. Подберите качественные материалы для ремонта квартиры, дома или коммерческого помещения.
How to Distinguish credible representative servers
In the today's digital setting, running of proxy tools has befit a crucial factor of activity of many professionals. Whether it's statistics parsing, account directorship, or bypassing restrictions, the consistent of the selected contrivance instantly determines the effectiveness of the prepare.
Types of agent servers https://atpimety.com
Routine car care often raises questions. I prefer reading clear information about regular inspections and repair work. While comparing automotive articles, I came across https://www.avtorepair.xyz . It is dedicated to car maintenance topics, which makes it relevant to drivers. These topics can help when planning future car care.
[img]https://doit-nails.com.ua/content/uploads/images/mankur-trendi1.jpg[/img]
Для старту в професії важливо правильно зібрати [url=https://magazin-prestige.in.ua/images/pages/?mater_ali_dlya_man_kuru__startoviy_nab_r_maystra_pochatk_vcya.html]стартовий набір майстра[/url] без зайвих витрат.
Системний підхід до вибору розхідників дозволяє уникнути конфліктів між формулами під час полімеризації.
Правильна комбінація підготовчих рідин та еластичних баз зводить до мінімуму ризик відшарувань біля кутикули.
У салонній роботі відмінну адгезію демонструє оригінальний [url=https://donolux.ru/include/wblog/?oxxi-gel-lak-golovne-bez-zajvogo.html]Oxxi гель-лак[/url] середньої густоти.
Коли потрібно скоротити час процедури, виручає [url=https://mirok.biz/modules/pgs/yak-obrati-gel-lak-3-v-1-odnofaznyj.html]гель-лак 3 в 1 однофазний[/url] без липкого шару.
При роботі з кольоровими системами важливо дотримуватися тонкого нанесення та запечатувати вільний край нігтя.
- Готові [url=http://prof4.ru/media/pgs/tipsi-na-nigti-shho-varto-znati-pered-pokupkoyu.html]тіпси на нігті[/url] мають тонку контактну зону біля кутикули для швидкої посадки
- Плавний перехід у зоні кутикули за допомогою фрези або м'якого бафа робить відростання непомітним
- Професійний [url=https://golodnaya-utka.od.ua/catalog/pages/kondicioner-dlya-volossya-shho-varto-znati-pered-pokupkoyu.html]кондиціонер для волосся[/url] та олії для кутикули завершують салонний догляд
- Формуйте б'юті-полицю свідомо, обираючи перевірений склад та оригінальні бренди
[img]https://doit-nails.com.ua/content/uploads/images/mankur-trendi1.jpg[/img]
Для старту в професії важливо правильно зібрати [url=https://magazin-prestige.in.ua/images/pages/?mater_ali_dlya_man_kuru__startoviy_nab_r_maystra_pochatk_vcya.html]стартовий набір майстра[/url] без зайвих витрат.
Коли всі позиції від дегідратора до топу підібрані правильно, покриття тримається до чотирьох тижнів.
Правильна комбінація підготовчих рідин та еластичних баз зводить до мінімуму ризик відшарувань біля кутикули.
Різноманітна [url=https://m-level.ru/wp-content/pgs/moon-praktichnij-gid.html]палітра Moon[/url] дозволяє легко підібрати як нюдові бази, так і яскраві тони.
Коли потрібно скоротити час процедури, виручає [url=https://mirok.biz/modules/pgs/yak-obrati-gel-lak-3-v-1-odnofaznyj.html]гель-лак 3 в 1 однофазний[/url] без липкого шару.
Поєднання правильної бази з топом із УФ-фільтром захищає світлі відтінки від пожовтіння та вигорання.
- Якісні [url=https://sdv-coffee.ru/blog/pgs/?verhni-formi-dlya-naroshhuvannya-nigtiv-shho-varto-znati-pered-pokupkoyu.html]верхні форми для нарощування нігтів[/url] мають зручну розмітку довжини
- Щоб нарощування трималося без відшарувань, важливо точно підбирати розмір форми під вигин нігтя
- Професійний [url=https://golodnaya-utka.od.ua/catalog/pages/kondicioner-dlya-volossya-shho-varto-znati-pered-pokupkoyu.html]кондиціонер для волосся[/url] та олії для кутикули завершують салонний догляд
- Формуйте б'юті-полицю свідомо, обираючи перевірений склад та оригінальні бренди
Нужны духи? купить духи оригинал минск с удобным выбором ароматов для мужчин и женщин. Вниманию покупателей представлены свежие, цитрусовые, древесные, цветочные и восточные композиции. Сравните предложения магазинов и найдите парфюм, который соответствует вашим предпочтениям.
Before acting on advice about buy tiktok likes, determine how other promotions, edits, reposts, or collaborations will be documented. Keep dated notes about whether the provider requests only public information and avoids passwords, codes, or unrelated account access. The best outcome is a clear record that can retain the original baseline when later content changes affect performance.
Instead of relying on rankings for buy real tiktok views, define whether replacement or refill terms apply and how eligibility is determined. A consistent scorecard can compare the process for correcting a wrong link before delivery begins and the consequences after work starts. The result should provide a defensible basis to keep the evaluation limited to what was actually observed and documented.
DarLink AI Review https://darlink-ai.carrd.co a detailed guide to setting up your virtual character and testing your memory within 48 hours. We analyze the creation of a profile, individual communication settings, saving dialogue details and the ability of artificial intelligence to remember information.
The Indian First League (IPL) is whole of the most electrifying cricket tournaments, attracting millions of cricket fans every season. Whether you follow every match or possess have a good time analysing group performances, having access to dependable IPL cricket poop can confirm your experience more engaging. If you are searching for an IPL betting site, betting website, or IPL betting app, IPL Betting Number is a website worth exploring.
At IPLBettingNumber.com, visitors can search IPL-related information, including cricket odds, mate predictions, fixtures, and other valuable updates. The website aims to lend cricket enthusiasts with a convenient appointment to bring up the rear notable match-related word throughout the IPL season.
Judgement befitting IPL betting sites can from time to time be confusing because many platforms offer different features and information. Beforehand choosing any IPL betting website or IPL betting app, users should carefully survey its credibility, security policies, pertinent terms, and constitutional requirements in their location. Those interested in IPL betting odds should also agree that odds can variation according to team combinations, sportswoman availability, position conditions, and copy situations.
Looking repayment for IPL betting predictions? Following group nature, head-to-head records, new performances, and player statistics can remedy cricket fans excel discern upcoming fixtures. You can also maintain track of IPL cricket odds and match schedules to wait informed in every nook the tournament.
People searching for an IPL betting APK, IPL betting ID, or IPL betting India message should each bear out platform authenticity and avoid sharing exclusive or economic details with unverified services. Muse on that cricket predictions are not till hell freezes over guaranteed, and betting involves pecuniary risks.
By https://www.iplbettingnumber.com/ to travel IPL-related updates, fixtures, odds information, and cricket capacity in possibly man place.
Enjoy the eagerness of IPL cricket responsibly. At all times follow district laws, put to rights advised decisions, and go into cricket as fun rather than a horse's mouth of guaranteed income.
БАНК-НЕВА - онлайн-площадка для сравнения займов, где пользователи могут сравнить условия микрозаймов и выбрать подходящий вариант до подачи заявки. Наши специалисты проводят анализ доступных программ МФО, проверяя основные параметры займов и условия их возврата. В подборках портала представлены микрозаймы на сумму от 1 000 до 30 000 рублей со ставкой не выше 0,8% в день. На страницах сервиса рассказываем, какие документы могут понадобиться, от чего зависит переплата и какие условия следует проверить заранее. Окончательное решение об одобрении принимает кредитор, поэтому гарантировать получение средств невозможно.
На БАНК-НЕВА собраны подборки с учётом потребностей заёмщиков. Пользователям доступны новые МФО, предложения для заёмщиков с испорченной КИ, а также организации с авторизацией через Госуслуги. Для удобного сравнения предусмотрен раздел [url=https://bankneyva.ru/bez-otkaza/]быстрые займы на карту без отказа[/url] где можно ознакомиться с условиями дистанционного оформления. Необходимо понимать, что название подборки не означает гарантированного получения денег. Кредиторы вправе оценивать кредитную историю, имеющиеся финансовые обязательства и достоверность предоставленных сведений. Поэтому рекомендуется внимательно сравнивать параметры кредитования.
Существенная часть материалов посвящена практическим рекомендациям по выбору надёжных МФО. Мы рассказываем, как убедиться в наличии МФО в официальном реестре ЦБ РФ, сверить её реквизиты с официальными данными и не попасться на уловки недобросовестных посредников. Также рассматриваем, как рассчитывается полная стоимость кредита, какие услуги могут увеличивать переплату и что необходимо проверить перед подписанием договора. До оформления микрозайма полезно рассчитать итоговую сумму возврата и сопоставить её со своими доходами. Полученные знания помогают осознанно выбирать условия кредитования, снижать финансовые риски и лучше понимать условия микрозаймов.