Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to export excel from asyExcel and download it as a zip package

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "asyExcel how to export excel and package it into zip package download", in daily operation, I believe many people in asyExcel how to export excel and package it into zip package download problems have doubts, small editor consulted all kinds of information, sorted out simple and easy to use operation method, hope to answer "asyExcel how to export excel and package it into zip package download" doubts helpful! Next, please follow the small series to learn together!

During the holiday period, I just used the export code at home, and after exporting it, there are multiple files, so I need to make a compressed package and download it to the customer. I looked up some information and posted this code here, which is equivalent to having a record.

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

//Get temporary directory of current system

private static final String FilePath = System.getProperty("java.io.tmpdir") + File.separator;

@RequestMapping(value = "/execute", method=RequestMethod.GET)

public void execute(HttpServletResponse response) {

//Used to store file path

List filePaths = new ArrayList();

//The ZIP file generated is called Demo.zip

String tmpFileName = "Demo.zip";

// zip file path

String strZipPath = FilePath + tmpFileName;

filePaths.add(strZipPath);

try {

//create zip output stream

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));

//declaration file collection is used to store excel files

List fileList = new ArrayList();

//generate excel file collection

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;

};

}

到此,关于"asyExcel怎么导出excel并打包成zip压缩包下载"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report