JAVA实现easyExcel下载压缩包

添加pom依赖

xml 复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>
<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.5</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.21</version>
</dependency>
<!--工具类-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.23</version>
</dependency>

实体类

java 复制代码
package com.example.mybatismysql8demo.excel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.math.BigDecimal;

@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Data
public class TemplateGoodsExcel implements Serializable {

    private String goodsCategory;

    private String goodsName;

    private Integer num;

    private BigDecimal price;

    public TemplateGoodsExcel(String goodsCategory,String goodsName, BigDecimal price, Integer num) {
        this.goodsName = goodsName;
        this.price = price;
        this.num = num;
        this.goodsCategory = goodsCategory;
    }

}

导出模版

zip下载工具类

java 复制代码
package com.example.mybatismysql8demo.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class ZipUtil {

    /**
     * 字节数组长度
     */
    private static final int BYTE_ARRAY_LENGTH = 1024;


    /**
     * 创建压缩文件
     * @param srcFile 源文件列表
     * @param zipFile 压缩文件
     */
    public static void zipFiles(File[] srcFile, File zipFile) {
        byte[] buf = new byte[BYTE_ARRAY_LENGTH];
        FileInputStream in = null;
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (File file : srcFile) {
                try {
                    in = new FileInputStream(file);
                    out.putNextEntry(new ZipEntry(file.getName()));
                    // 支持中文  解决文件名乱码问题
                    out.setEncoding("GBK");
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                } catch (Exception e) {
                    log.error(String.format("压缩文件出错 01:{}%s", e));
                } finally {
                    out.closeEntry();
                    assert in != null;
                    in.close();
                    //删除源文件
                    FileUtil.del(file);
                }
            }
        } catch (IOException e) {
            log.error(String.format("压缩文件出错 02:{}%s", e));
        }finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(String.format("压缩文件出错 02:{}%s", e));
                }
            }
        }
    }

    /**
     * 从浏览器下载压缩文件
     * @param file 文件对象
     * @param response 响应对象
     * @param isDelete 是否删除源文件
     * @throws IOException io异常
     */
    public static void downloadZipFile(File file, HttpServletResponse response, boolean isDelete) throws IOException{
        OutputStream toClient = null;
        try(InputStream inputStream =new FileInputStream(file)) {
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
            int len;
            byte[] buffer = new byte[1024];
            while((len=inputStream.read(buffer))>0){
                toClient.write(buffer,0,len);
            }
            toClient.flush();
        } catch (IOException ex) {
            log.error(ex.getMessage());
        } finally{
            if(toClient!= null){
                toClient.close();
            }
        }
        //在所有流都关闭后再删除文件
        if(isDelete && file.exists()) {
            FileUtil.del(file);
        }
    }
}

执行方法

java 复制代码
package com.example.mybatismysql8demo.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.mybatismysql8demo.excel.TemplateGoodsExcel;
import com.example.mybatismysql8demo.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@RestController
public class EasyExcelController {

    /**
     * 浏览器下载
     * @param response
     */
    @RequestMapping(value = "easyExcelExport", method = RequestMethod.GET)
    private void browserDownload(HttpServletResponse response){
        //数据
        List<TemplateGoodsExcel> data = new ArrayList<>();
        data.add(new TemplateGoodsExcel("零食","辣条",new BigDecimal(10),100));
        data.add(new TemplateGoodsExcel("水果","葡萄",new BigDecimal(16),50));
        data.add(new TemplateGoodsExcel("水果","苹果",new BigDecimal(20),150));
        //按照分类分组
        Map<String, List<TemplateGoodsExcel>> collect = data.stream().collect(Collectors.groupingBy(TemplateGoodsExcel::getGoodsCategory));
        //模版路径
        String templatePath = "E:\\模板\\商品.xls";
        //文件下载路径
        String path = "E:\\下载\\";
        //文件集合
        File[] fileArray = new File[collect.size()];
        //小标
        int index = 0;
        for (Map.Entry<String, List<TemplateGoodsExcel>> value : collect.entrySet()) {
            //判断文件夹是否存在
            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.mkdir();
            }
            //导出文件名
            String fileName = path +  value.getKey() + "_" + System.currentTimeMillis() + ".xls";
            //导出
            ExcelWriter excelWriter = EasyExcelFactory.write(fileName).excelType(ExcelTypeEnum.XLS).withTemplate(templatePath).build();
            WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();
            //表格数据
            excelWriter.fill(value.getValue(), writeSheet);
            Map<String,Object> map = new HashMap<>(1);
            map.put("goodsName", value.getKey());
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();
            fileArray[index] = new File(fileName);
            index++;
        }
        //打包文件名
        String zipPath = path + System.currentTimeMillis() + "_" + "物品信息.zip";
        //文件打包
        ZipUtil.zipFiles(fileArray, new File(zipPath));
        //浏览器下载
        File file = new File(zipPath);
        try {
            ZipUtil.downloadZipFile(file, response, true);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
相关推荐
小冉在学习9 分钟前
day53 图论章节刷题Part05(并查集理论基础、寻找存在的路径)
java·算法·图论
y5236489 分钟前
Javascript监控元素样式变化
开发语言·javascript·ecmascript
IT技术分享社区39 分钟前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
极客代码42 分钟前
【Python TensorFlow】入门到精通
开发语言·人工智能·python·深度学习·tensorflow
疯一样的码农1 小时前
Python 正则表达式(RegEx)
开发语言·python·正则表达式
代码之光_19801 小时前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi1 小时前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
&岁月不待人&1 小时前
Kotlin by lazy和lateinit的使用及区别
android·开发语言·kotlin
StayInLove1 小时前
G1垃圾回收器日志详解
java·开发语言
对许1 小时前
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder“
java·log4j