您好,登錄后才能下訂單哦!
這篇文章主要介紹“asyExcel怎么導出excel并打包成zip壓縮包下載”,在日常操作中,相信很多人在asyExcel怎么導出excel并打包成zip壓縮包下載問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”asyExcel怎么導出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;
};
}
到此,關于“asyExcel怎么導出excel并打包成zip壓縮包下載”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。