easyExcel导出excel文件并打包成zip压缩包下载

package com.business.testExcelPort;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;

import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @ClassName DownLoad
 * @Deacription TODO
 * @Author SEN
 * @Date 2020/2/10 0010 17:49
 * @Version 1.0
 **/

@Controller
@RequestMapping("/download")
@Slf4j
public class DownLoad {
    private Logger Log = Logger.getLogger(DownLoad.class);
    // 获取当前系统的临时目录
    private static final String FilePath = System.getProperty("java.io.tmpdir") + File.separator;
    
    @RequestMapping(value = "/execute", method=RequestMethod.GET)
    public void execute(HttpServletResponse response) {
    	// 用于存放文件路径
        List<String> filePaths = new ArrayList<>();
        //生成的ZIP文件名为Demo.zip
        String tmpFileName = "Demo.zip";
        // zip文件路径
        String strZipPath = FilePath + tmpFileName;
        filePaths.add(strZipPath);
        try {
        	//创建zip输出流
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
            //声明文件集合用于存放excel文件
            List<File> fileList = new ArrayList<File>();
            //生成excel文件集合
            for (int i = 0; i < 10; i++) {
            	// 生成随机文件名
                String filename = FilePath + generateRandomFilename() + ".xlsx";
                // 将文件路径保存
                fileList.add(creatFile(filename));
                filePaths.add(filename);
                List<DataOne> list = new ArrayList<>();
                for (int j = 0; j < 10; j++) {
                	// 造一些表格数据,一般是从数据库查出来的list集合数据
                    DataOne dataOne = new DataOne();
                    //。。。
                    list.add(dataOne);
                }
				// 使用easyexcel生成excel文件
				writeExcel(newFile, DataOne.class, list,ExcelTypeEnum.XLS);                
            }
            byte[] buffer = new byte[1024];
            //将excel文件放入zip压缩包
            for (int i = 0; i < fileList.size(); i++) {
                File file = fileList.get(i);
                FileInputStream fis = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(file.getName()));
                //设置压缩文件内的字符编码,不然会变成乱码
                out.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容,打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
            out.close();
            //下载zip文件
            this.downFile(response, tmpFileName,filePaths);
        } catch (Exception e) {
        	// 下载失败删除生成的文件
        	deleteFile(filePaths);
            Log.error("文件下载出错", e);
        }
    }


    /**
     * 文件下载
     *  @param response
     * @param str
     * @param filePaths
     */
    private void downFile(HttpServletResponse response, String str, List<String> filePaths) {
        try {
            String path = FilePath + str;
            File file = new File(path);
            if (file.exists()) {
                InputStream ins = new FileInputStream(path);
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                response.setContentType("application/x-download");// 设置response内容的类型
                response.setHeader(
                        "Content-disposition",
                        "attachment;filename="
                                + URLEncoder.encode(str, "UTF-8"));// 设置头部信息
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();// 这里一定要调用flush()方法
                ins.close();
                bins.close();
                outs.close();
                bouts.close();
                deleteFile(filePaths);
            }
        } catch (IOException e) {
        	deleteFile(filePaths);
            Log.error("文件下载出错", e);
        }
    }
	//创建文件File对象
    private File creatFile(String filePath) {
        File file = new File(filePath);
        return file;
    }
	//生成随机文件名
    public String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();
        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";

        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);
        return RandomFilename;
    }
    //删除文件
    public static boolean deleteFile(List<String> filePath){
        boolean result = false;
        for (String pathname:filePath){
            File file = new File(pathname);
            if (file.exists()) {
                file.delete();
                result = true;
            }
        }
        return result;
    }
   	/**
     * @Title: writeExcel
     * @Description: 写入excel文件到输出流web端
     *
     */
    private void writeExcel(OutputStream outputStream, Class<?> clazz, List<?> datalist,ExcelTypeEnum excelType,String sheetName) throws IOException {
        EasyExcel.write(outputStream, clazz).excelType(excelType).sheet(sheetName==null ? "sheet1":sheetName).doWrite(datalist);
        outputStream.flush();
    }

    /**
     * @Title: writeExcel
     * @Description: 写入excel到本地路径
     */
    private void writeExcel(File newFile, Class<?> clazz, List<?> datalist,ExcelTypeEnum excelType) {
        EasyExcel.write(newFile, clazz).excelType(excelType).sheet("sheet1").doWrite(datalist);
    }

    /**
     * @Title: readExcel
     * @Description: 读取excel内容(从输入流)
     */
    private List<?> readExcel(InputStream inputStream, Class<?> clazz, ReadListener<?> listener) {
        List<?> list = null;
        list = EasyExcel.read(inputStream, clazz, listener).sheet().doReadSync();
        return list;
    };
}


### easyExcel 导出 Excel 实际生 Zip 文件的解决方案 当使用 EasyExcel 进行多文件导出将其打包 ZIP 文件时,可以按照以下方法实现完整的功能。 #### 1. 多个 Excel 文件压缩为 ZIP 文件 为了满足需求,可以通过 Java 流的方式将多个 Excel 文件写入到一个 ZIP 输出流中。以下是具体实现方式: - 使用 `ZipOutputStream` 创建一个 ZIP 压缩包。 - 将每个 Excel 文件通过 EasyExcel 工具单独生将其作为字节流写入到 ZIP 输出流中。 - 关闭所有流以确保数据完整保存。 下面是具体的代码示例[^1]: ```java import com.alibaba.excel.EasyExcel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ExcelToZipExporter { public static void exportMultipleExcelsAsZip(String[] fileNames, List<List<Object>> dataLists, ServletOutputStream outputStream) throws IOException { try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) { for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; List<Object> dataList = dataLists.get(i); ByteArrayOutputStream excelByteArrayOutputStream = new ByteArrayOutputStream(); EasyExcel.write(excelByteArrayOutputStream).sheet("Sheet").doWrite(dataList); // 写入Excel数据 byte[] excelBytes = excelByteArrayOutputStream.toByteArray(); ZipEntry entry = new ZipEntry(fileName); zipOut.putNextEntry(entry); zipOut.write(excelBytes); zipOut.closeEntry(); excelByteArrayOutputStream.close(); // 清理临时流 } } catch (Exception e) { throw new RuntimeException("Failed to generate ZIP with multiple Excel files", e); } } } ``` 上述代码实现了将多个 Excel 文件打包 ZIP 文件的功能。每份 Excel 数据被独立生通过内存流传递给 ZIP 输出流。 --- #### 2. 性能优化建议 在处理大量数据时,需注意以下几个方面以提升性能和稳定性[^3]: - **分块导出**: 如果单个 Excel 文件的数据量较大,可采用分页或分块机制逐步导出数据,从而降低内存压力。 - **启用磁盘模式**: 避免使用 `.inMemory(Boolean.TRUE)` 方法(可能导致 OOM),而是让 EasyExcel 自动切换至磁盘暂存模式。 - **调整导出参数**: 如字体大小、列宽等设置可根据实际情况进行微调,进一步缩小最终文件体积。 对于线上环境部署问题,还需确认服务器端已安装必要字体支持以及适当配置 JVM 参数以便于应对高发请求场景下的资源消耗情况[^4]。 --- #### 3. 注意事项 - 确保输入列表长度一致:即 `fileNames` 数组与 `dataLists` 列表应保持一一对应关系。 - 设置合理的线程池管理策略,在大规模批量任务执行过程中防止因过度创建子进程而导致系统崩溃风险增加。 --- ###
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值