最近项目内有需要导出多个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://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.
Ihqkedjf PXQRlengbumo.topPXQR anwctgf hbjoarc PFQR194445PFQR www.google.com
News129.online is a modern online publication where readers can discover informative articles, fresh updates, and interesting stories. The website provides access to fresh publications covering noteworthy developments, useful topics, practical information, and subjects that may interest a wide audience.
The website is intended for readers interested in discovering useful information, exploring different subjects, and keeping up with current developments. The platform is available at https://news129.online. News129.online strives to provide a simple and convenient experience for discovering interesting content, with new materials expanding the website over time.
Перед запуском рекламы стоит проверить весь путь заявки. Начните с телефона клиента и закончите карточкой обращения в CRM.
1. Откройте сайт со смартфона и попробуйте отправить форму с пустым обязательным полем. Понятно ли, что нужно заполнить? Затем заполните форму, укажите свой номер и добавьте комментарий «Тест с телефона». По этой фразе будет легко найти обращение.
2. Посмотрите, сколько раз сработала цель «Заявка» в Метрике. Ожидаемый результат — одно достижение цели после того, как форма приняла данные. Если засчитались обе попытки, проверьте, какое событие запускает цель.
3. Откройте вместе с менеджером карточку тестовой заявки в CRM. Проверьте, дошли ли номер телефона и текст комментария. Если по правилам отдела у каждой новой заявки должен быть ответственный, посмотрите, кому она назначена.
Если вы только готовите задание на сайт, запишите эти три проверки в требования к форме. У [url=https://insidet.ru/]веб-студии INSIDET[/url] на главной указаны цены на разработку и этапы подключения аналитики.
Попал в реестр рнп? защита от включения в рнп анализ обстоятельств закупки, подготовка документов, составление возражений и защита интересов участника в ФАС. Профессиональное сопровождение на всех этапах рассмотрения дела.
[b][url=https://gazvmoskve.ru]закись азота купить баллон 5л[/url][/b]
Может быть полезным: https://gazvmoskve.ru или [url=https://gazvmoskve.ru]баллон веселящий газ москва[/url]
[b][url=https://gazvmoskve.ru]седация закисью азота в стоматологии[/url][/b]
[b][url=https://teselectro.ru]шина нулевая в корпусе[/url][/b]
Лампа таблетка используется в совместимых светильниках для организации внутреннего или наружного освещения. Качественные электротехнические материалы и комплектующие помогают обеспечить стабильную работу системы. Грамотный подбор помогает оптимизировать бюджет проекта и соблюсти необходимые технические требования.
Может быть полезным: https://teselectro.ru/shop/klimaticeskie-i-inzenernye-sistemy/otopitelnye-pribory-ventiliaciia-texnologiceskie-i-inzenernye-sistemy/kabel-nagrevatelnyi-i-aksessuary/nagrevatelnyi-kabel/product/esu-75f-50-3220743 или [url=https://teselectro.ru]лампа газоразрядная[/url]
[b][url=https://teselectro.ru/shop/kabelenesushhie-sistemy/sistemy-dlia-prokladki-kabelia/truby-dlia-prokladki-kabelia/truba-gofrirovannaia-plastikovaia/product/7ve920100-3351170]труба пнд[/url][/b]
Электрооборудование электромонтажника востребован при выполнении электромонтажных работ на объектах различного назначения. Для проекта важно учитывать рабочие параметры, особенности установки и требования технической документации. Ассортимент позволяет подобрать подходящий вариант для строительства, ремонта или модернизации объекта.
For quite a while I have been collecting coin collecting and antiques. I always enjoy reading about the stories behind rare coins and unique antiques.
While exploring different websites I found https://groshi.xyz . It was exactly what I was looking for. There was quite a bit of useful information about rare collectibles.
What impressed me most was the detailed explanations. Although the project is not fully launched yet, it has great potential.
From what I understand the website will officially launch soon. I'm looking forward to it, because I'm sure there will be many more expert information for coin collectors.
If you're passionate about coin collecting or antiques, I think following this site. I'm looking forward to seeing how the project grows.
Надежный поставщик, которому можно доверять крупные и сложные заказы.
https://telegra.ph/Pishchevaya-stal-11-02
A professional international business education and consulting platform about management training: https://mbocentre.com
We know where to find practical business expertise.
This platform offers applied management frameworks that are
designed for entrepreneurs and leaders.
The content is especially valuable for readers seeking structured leadership guidance rather than
surface-level theory.
interesting for a very long time
_________________
[url=https://1winazerbaijanbonus.study/money-x/]МаниХ[/url]
демонтаж зданий и сооружений демонтаж старого здания
снос и демонтаж зданий и сооружений снос кирпичного здания
Ищете отель на час https://spb.60minut.ru в Санкт-Петербурге? Ознакомьтесь с гостиницами и апартаментами с почасовой оплатой, сравните цены, расположение и условия проживания. Подберите номер для отдыха, деловой встречи или остановки между поездками. Удобные варианты краткосрочной аренды жилья.
онлайн-журнал https://pedia.com.ua для тех, кто интересуется современным образом жизни, здоровьем и саморазвитием. Полезные статьи о семье, воспитании детей, красоте, домашнем хозяйстве, садоводстве, технологиях и повседневных вопросах. Новые идеи, советы и интересные материалы для широкой аудитории.
Ищете отель на час https://spb.60minut.ru в Санкт-Петербурге? Ознакомьтесь с гостиницами и апартаментами с почасовой оплатой, сравните цены, расположение и условия проживания. Подберите номер для отдыха, деловой встречи или остановки между поездками. Удобные варианты краткосрочной аренды жилья.