最近项目内有需要导出多个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等,以后需要再修改吧。牛马不易,摸鱼续命
凡是过往,皆为序章!
баня из клееного под ключ купить баню из бруса под ключ
A detailed overview undress ai of Undress AI and DeepNude technologies. Learn about image generation features, limitations of artificial intelligence, privacy policies, photo upload security, and terms of use.
Нужен сыр? сыр оптом в Москве для магазинов, кафе, ресторанов и предприятий общественного питания. Широкий выбор твёрдых, мягких и полутвёрдых сортов, выгодные условия закупки, оптовые цены и доставка продукции.
Hello!
This post was created with.
https://nu-11071.s3.us-east-2.amazonaws.com/1/dukungan-diabetes-tipe2.html
Good luck :)
[url=https://ai-candy.app/]Candy AI[/url] provides AI-powered characters for relationship-themed conversations, fictional relationships and interactive storytelling. You can choose an existing companion or create a personalised companion. The operator is EverAI Limited, registered in Malta under number C107181. The service is intended for adults aged 18 or over who meet the applicable age-of-majority requirements.
What You Can Test Before Subscribing
The documented free-user guide lists up to five messages in chat, shared across all characters; one custom AI character; and one image generation. Verify your available access inside your account.
Plan your first exchanges: start with an open-ended question, then follow up with a clear instruction about tone. Notice whether the next reply reflects your instruction. That provides a practical way to assess the character’s voice before buying a paid plan.
Customise a Virtual Character
Open Create Character and select the Realistic option or the Anime option. The service description lists character settings for hairstyle, hair colour, eye colour, voice, character traits and hobbies.
Begin with a clear personality idea, then add a suitable reply style. For example: “Personality: upbeat. Interests: travel. Replies: concise, with one relevant question.”
Specific instructions give you a clear reference point to evaluate. The support documentation describes character descriptions, your own messaging style and regenerating a reply as methods to influence the tone. Change one instruction at a time to assess the effect.
Clone Chat, Reset Chat and Conversation Memory
Clone Chat copies the existing chat, including the conversation so far. You can continue the copy in a different direction while keeping the original thread.
For a writing exercise, retain one version as a light-hearted exchange and steer the duplicate towards an adventure. Compare how the companion responds to the changed premise.
The chat-history guide presents Reset Chat as starting the interaction afresh, while Delete Chat permanently removes the chat thread. According to the documentation, there is no option to clear the history while fully retaining long-term conversation memory.
Pictures, Voice and Video
Generate Image organises the character catalogue into Girls, Anime and Guys. Choose an available companion to begin your image request.
The token guide lists image generation, playing voice notes, beta voice calling and video generation among token-based features. It also describes turning a suitable chat-generated image into a video clip. Check the token cost for the operation you want before spending your balance.
Build Your Video uses ready-made options for character, action, location and another participant. Select the available options, then click Generate video. The output is saved in My Generations. The final clip may differ from the presets.
Candy Shorts provides scripted short scenarios featuring virtual companions. Episodes typically last under two minutes and sit outside your chats. Viewing an episode does not affect your chat history or character relationship.
Subscription Costs: Check the Upfront Charge
The published subscription offer, checked on 13 November 2026, showed:
Monthly plan: $9.99 for the first month, then $13.99 per month.
Quarterly plan: $26.97 paid upfront, working out at $8.99 per month.
Annual plan: $47.88 paid upfront, working out at $3.99 per month.
Check the total charged upfront against the monthly equivalent. Subscriptions renew automatically; additional local taxes may be charged. Review the checkout total before paying.
Plan Your Token Budget
The paid-user guide lists unlimited chat messages and 100 tokens per month. The token refresh follows your original subscription date. Users on an annual plan also receive 100 tokens each month.
Regular text chatting does not spend tokens, according to the help documentation. Once you run out of tokens, text chatting remains available with a current paid plan; extra credits apply to further token-based activities.
Choose a separate budget for top-ups. Before another media request, consider whether a clearer instruction would help you assess the tool. Review the applicable token cost for the selected operation.
Cancel Automatic Renewal
The documented account route points to My Profile > Settings > Unsubscribe. Follow the confirmation steps to finish the cancellation.
As explained by the help centre, cancellation prevents subsequent automatic renewals, and Premium continues until the current paid period ends. A request to return a previous payment is a separate process and requires review.
The content-retention guide says ending the subscription keeps your chats, images, characters and history while the account remains active. Unused tokens stay on the account, but the balance is not displayed on the Free service and using them again requires a Premium subscription.
Data Use and the Nature of AI Characters
The Privacy Notice describes user messages, generated replies and companion settings. The document states that technical service providers, including language-model providers, may receive message content. It also permits processing anonymised or de-identified conversations for training-data preparation and technology improvement.
Use invented character information for creative scenarios, and keep account credentials and financial information out of your prompts. These precautions reflect the guidance about sensitive information in the service’s terms.
The Terms define Candy AI as entertainment. Its characters generate fictional interactions and do not have real feelings. To make an initial session worthwhile, assess one character, a specific reply style and one media feature, then evaluate the experience against the total subscription cost and your token budget.
[url=https://vikingluck-casino.com][img]https://gamblizard.de.com/wp-content/uploads/img-3/viking-luck-casino-logo-gamblizardde.png[/img] [/url]
Viking Luck Casino — Claim Your Share of the Spoils
Top-tier pokies, full table range and round-the-clock live dealers.
Proven game studios, fast banking, terms you can actually read.
Start Your Run Here
— A welcome haul of A$2,000 plus 200 spins across three deposits
— Deposit one is matched dollar for dollar to A$750, with 100 spins on top
— 10% weekly cashback on net losses, paid every Monday
— Tournaments every week and seasonal raids worth A$50,000
— 35x wagering over 14 days — laid out plainly, not hidden away
-Login:https://vikingluck-casino.com/login
-Bonuses:https://vikingluck-casino.com/bonuses
-App:https://vikingluck-casino.com/app
-Slots:https://vikingluck-casino.com/slots
Withdrawals processed in under 24 hours. Support available 24/7.
Vikings didn't sit out the storm — they sailed through it.
Take your welcome offer now.
Play smart. Set your limits. 18+.
[url=https://vikingluck-casino.com][img]https://gamblizard.de.com/wp-content/uploads/img-3/viking-luck-casino-logo-gamblizardde.png[/img] [/url]
Viking Luck Casino — Claim Your Share of the Spoils
A sharp pokie library, classic casino tables and live dealers on deck 24/7.
Trusted studios, quick payments, conditions written in plain English.
Your Raid Starts Here
— A welcome haul of A$2,000 plus 200 spins across three deposits
— Deposit one is matched dollar for dollar to A$750, with 100 spins on top
— Weekly cashback of 10% on net losses, credited Mondays
— Weekly leaderboards and seasonal events with A$50,000 on the line
— Playthrough is 35x with a 14-day window, stated clearly from the start
-Login:https://vikingluck-casino.com/login
-Bonuses:https://vikingluck-casino.com/bonuses
-App:https://vikingluck-casino.com/app
-Slots:https://vikingluck-casino.com/slots
Cashouts cleared inside 24 hours. Help on hand any hour.
Vikings didn't sit out the storm — they sailed through it.
Take your welcome offer now.
Play smart. Set your limits. 18+.
[url=https://vikingluck-casino.com][img]https://gamblizard.de.com/wp-content/uploads/img-3/viking-luck-casino-logo-gamblizardde.png[/img] [/url]
Viking Luck Casino — Fortune Rewards the Fearless
Premium pokies, classic tables and a live dealer floor that never closes.
Name-brand studios, fast cashouts and rules you won't need a lawyer for.
Your Raid Starts Here
— Welcome package up to A$2,000 + 200 free spins across your first three deposits
— First deposit matched 100% up to A$750, with 100 spins on selected pokies
— 10% back on net losses every week, landing each Monday
— Regular tournaments and seasonal raids carrying A$50,000 prize pools
— 35x wagering over 14 days — laid out plainly, not hidden away
-Login:https://vikingluck-casino.com/login
-Bonuses:https://vikingluck-casino.com/bonuses
-App:https://vikingluck-casino.com/app
-Slots:https://vikingluck-casino.com/slots
Withdrawals processed in under 24 hours. Support available 24/7.
The Vikings didn't wait for the tide to turn — they rowed into it.
Take your welcome offer now.
Play smart. Set your limits. 18+.
Перейти к первоисточнику: https://talashjob.com/employer/e-news/
Which meme coins https://top-meme-coins.com have become the most popular, and how have their prices changed? A review of the historical peaks and valleys of Dogecoin, Shiba Inu, Pepe, and other projects. We examine the influence of social media, investor interest, and market sentiment on cryptocurrency prices.
Обновлено сегодня: https://gogs.xn--feld-4qa.de/rosemarykalesk
Узнать свежие подробности: юрист для заседания уфас по рнп
Перейти к материалу: https://dreamriseproperties.in/author/eugeniorickett/
Читать подробный разбор: https://zaschita-rnp.ru
The top 10 hiking apps https://sergfrost.substack.com/p/10-best-hiking-trail-apps-for-2027/ for 2027, with a detailed overview of features and capabilities. Explore apps for route planning, GPS navigation, terrain viewing, and offline maps. Find the perfect solution for hikes of varying difficulty levels.
Обзор по теме https://ochen-vkusno.com/pechene/pro-stoun-kak-sobrat-tselniy-interer-iz-plitki-tsveta-formati-fakturi.html — лестница из керамогранита в интерьере.
Coming to this with low expectations and being pleasantly surprised by the substance, and a stop at flavorjourneyhub continued exceeding expectations, the recalibration of expectations upward across multiple positive readings is one of the actual rewards of careful browsing and this site is providing that recalibration at a steady rate apparently.
Reading this on the train into work was a better use of the commute than my usual choices, and a stop at mjdue3 extended that commute reading well, content that improves transit time rather than just filling it is content with practical benefit and this site has earned its place in my morning commute reading rotation.
A useful discussion of poker starts with the conditions a reader can actually check. Look at cash games, tournament structures, blind levels, rake, player traffic, and bankroll limits. Where a description is unclear, consult the operator or the game rules before proceeding.
Readers looking into this topic can visit [url=https://flashroyal.us/poker/]online pai gow poker for money[/url]. Availability and terms may change. Use a predetermined entertainment budget and avoid trying to recover previous losses.
I've been looking into [url=https://proastrology.bid/]astrology readings[/url] recently and realized there's a lot more to it than just knowing your sun sign.
Figured I'd share in case anyone else is exploring the same stuff.