假期期间自己在家撸码,刚好用到了导出,导出来之后是多个文件,所以需要打成压缩包并下载来给客户。查阅了一些资料,把这段代码贴在这,相当于有个记录吧。

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 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 fileList = new ArrayList();

//生成excel文件集合

for (int i = 0; i < 10; i++) {

// 生成随机文件名

String filename = FilePath + generateRandomFilename() + ".xlsx";

// 将文件路径保存

fileList.add(creatFile(filename));

filePaths.add(filename);

List 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 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 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;

};

}

java 导出表格打包zip文件下载_asyExcel导出excel并打包成zip压缩包下载相关推荐

  1. JAVA实现把指定文件夹下的所有文件压缩成zip包

    1.代码如下: package cn.gov.csrc.base.util;import java.io.BufferedInputStream; import java.io.BufferedOut ...

  2. 使用Hutool生成多个excel文件合并成zip压缩包下载

    这几天有个业务需要把项目里数据生成excel后打包zip下载,但之前的项目基本都是用Apache自带的poi去做,这个项目引入Hutool工具,所以就用了Hutool的功能去做了,跟之前相比感觉省事了 ...

  3. php导出表格是乱码怎么办,数据库导出excel表格是乱码怎么办-Excel表格乱码问题怎么解决?...

    POI导出excel表时文件名变成乱码怎么办 在乱码的表格上键-用记事本打 2 这里会看到里面的文字都恢复了. 3 接下来文件-另存为 4 另存的时候刻改一下文件名,这里改成1副本,格式为txt,然后 ...

  4. 服务器导出表格无法打开php,phpSpreadsheet导出xlsx无法打开的解决办法

    PhpSpreadsheet是什么?一句话解释就是:一个用纯 PHP 来实现读取.写入电子表格文件(xls\xlsx等)的PHP库. 为什么不用PHPExcel? 也就是一句话:PHPExcel太故老 ...

  5. Java多级动态导出表格,优化版

    动态导出表格 接上次发布的导出做了一些优化和加入一些功能 优化:修改了一些bug,和优化判断逻辑 新功能:加入样式自定义,可自定义表头和表内容样式 新方法方法名为:summaryTableExport ...

  6. 根据查询结果导出表格数据

    根据查询结果导出表格数据 bootstrap table 自定义导出excle 甲方非要根据查询结果导出数据 $("#导出按钮").on('click', function () ...

  7. 关于springmvc下服务器文件打包成zip格式下载功能

    关于springmvc下服务器文件打包成zip格式下载功能 2016年09月21日 11:22:14 toxic_guantou 阅读数:5731更多 个人分类: 技术点存储 版权声明:本文为博主原创 ...

  8. springboot 后台把数据制作成excel表格并打成压缩包下载

    项目里面遇到要把数据做成资料卡片,然后写入单独的excel文件,之后打成压缩包下载.这个过程记录一下,希望对大家有用. 1.在controller里面开个口子,接收客户端的请求.由于vue里面用了do ...

  9. php zip解压原理,PHP ZipArchive实现解压缩zip文件

    PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...

最新文章

  1. 2022-2028年中国钢铁冶炼行业市场研究及前瞻分析报告
  2. Python+OpenCV实现AI人脸识别身份认证系统(3)—训练人脸识别模型
  3. 使用Go内置库实现简易httpbin功能
  4. Metadata GC Threshold导致的full gc分析
  5. 单链表快速排序算法实现
  6. python subplot_气象编程 | 一个简单的风数据处理和分析案例(Python版)
  7. 理解python的with as 语句
  8. Vulhub搭建小记
  9. 第四范式受邀成为5G消息工作组成员
  10. redis部署架构总结
  11. python-环境篇-Anaconda的安装
  12. androidStudio快捷键概览
  13. Voxengo音频插件合集:Voxengo Total Bundle Mac
  14. python wps linux_体验WPS for Linux
  15. plc编程不是c语言,PLC编程中的五个常见问题
  16. 两阶段网络DEA及其计算
  17. ABP (ASP.NET Core 5.x + Vue)小白基础入门(一)
  18. 启动react项目报找不到文件的错误
  19. 岁月温柔-3 清明节医院复查,去昆明过冬是否会是一种奢望?
  20. 4 数据校验和防碰撞

热门文章

  1. AttributeError: module 'socketio' has no attribute 'Server'
  2. ubuntu解决tensorflow提示未编译使用SSE3、SSE4.1、SSE4.2、AVX、AVX2、FMA的问题
  3. freqz()计算M点滑动平均滤波器的频率响应
  4. guava 对集合的支持
  5. 检查本地是否存在某个文件
  6. 中国的脑部研究--脑网络组图谱
  7. AIR学习教程(一)
  8. 计算纯文本情况下RichTextBox实际高度的正确方法(.NET)
  9. [转载] Java7中增加的新特性
  10. try catch finally的理解