问题简述
之前系统里做的导出都是千篇一律的所有文件导在一个excel里,有现成的工具,现成的逻辑。
突然有那么一天,一切都不再现成了,我得把数据们导出为压缩包,一人一个Excel谁也不干涉谁。研究和参考了一下网上大神们的思路和逻辑以及代码,最后做出一版符合现有需求和现有系统的接口。希望能帮到需要的、同为初级菜菜的兄弟姐妹。水平有限不足之处望大家批评指正,批评使人进步,进步使人涨薪
先上导出效果(名字保密啦,大概就是这个熊样)
开始 撸起袖子干
思路
1.先在工作路径的适当位置搞一个临时文件夹
2.把所有组装好的数据丢进去
3.打包这个临时文件夹并把.zip文件也放在临时文件夹下面
4.压缩包输出流,临时文件夹及其里所有东西删除掉
编写工具类
package com.gdj.ggfw.serv.web.rest.util.ExcelUtils;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import org.apache.poi.ss.usermodel.Workbook;
public class ZipExportUtils {
/**
* 导出--使用easypoi,有模板
* @param sheetList、、
* @param templatePath
* @param filename
* @return
*/
public static String getExportResult(List<List<Map<String, Object>>> sheetList, String templatePath, String filename) throws IOException {
// 加载模板
TemplateExportParams params = new TemplateExportParams(templatePath, true);
// 组装数据
Map<String, Object> excelMap = new HashMap<>();
for (int i = 0; i < sheetList.size(); i++) {
String sheetname = "sheet" + (i + 1);
List<Map<String, Object>> list = sheetList.get(i);
excelMap.put(sheetname, list);
}
// easypoi方法--得到workbook
Workbook workbook = ExcelExportUtil.exportExcel(params, excelMap);
// workBook写入file
FileOutputStream fileOutputStream = new FileOutputStream(filename);
workbook.write(fileOutputStream);
fileOutputStream.close();
return "导出成功";
}
/**
* 将多个Excel打包成zip文件
* @param srcfile
* @param zipfile
*/
public static void zipFiles(List<File> srcfile, File zipfile) {
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.size(); i++) {
File file = srcfile.get(i);
FileInputStream in = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出文件流以及关闭闭流;
*/
public static void closeFile(HttpServletResponse response,String serverPath, String str) {
try {
String path = serverPath +"/"+ str;
File file = new File(path);
if (file.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int length = inputStream.read(data);
inputStream.close();
response.setContentType("application/zip");
OutputStream stream = response.getOutputStream();
stream.write(data);
stream.flush();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
response.sendRedirect("../error.jsp");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
File file1=new File(serverPath);
// 删除临时目录
deleteExcelPath(file1);
}
}
/**
* 删除目录下所有的文件;
* @param file
*/
public static boolean deleteExcelPath(File file){
String[] files = null;
if(file != null){
files = file.list();
}
if(file.isDirectory()){
for(int i = 0; i < files.length; i ++){
boolean bol = deleteExcelPath(new File(file,files[i]));
if(bol){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
}
}
return file.delete();
}
}
控制层代码
/**
* 导出(压缩包)
* @param response
* @param ids
* @return
*/
@PutMapping("/exportZip")
@Timed
public void exportProContractManagement(HttpServletResponse response , @RequestBody List<String> ids) throws IOException {
// 加载模板
String templatePath = "xxx/xxx.xls";
// 设置下载excel的临时文件夹
String dirId = UUID.randomUUID().toString();
MultipartConfigFactory multipartConfigFactory = new MultipartConfigFactory();
//获取程序当前路径(当前工作目录)
String serverPath = System.getProperty("user.dir") + "/" + dirId;
File fileTemp = new File(serverPath);
if(!fileTemp.exists()){
fileTemp.mkdirs();
}
multipartConfigFactory.setLocation(serverPath);
multipartConfigFactory.createMultipartConfig();
serverPath = serverPath.replace('\\', '/');
// 声明一个集合,用来存放多个Excel文件路径及名称
List<File> srcfile = new ArrayList<File>();
// 得到路径下的文件,如果不存在创建文件夹
File file = new File(serverPath);
if (!file.exists()) {
file.mkdir();
}
// 打印日志
logger.debug("\n"+"临时路径---------------------------" + serverPath);
// 组装数据
List<List<Map<String, Object>>> sheetList = null;
for(int i = 0 ; i < ids.size() ; i ++){
// 单条数据查询(service层中获取数据并组装完成,此处不赘述)
sheetList = managementService.exportProContractManagement(ids.get(i));
if (sheetList.size() == 0) {
// 删除临时路径(为防止报错后临时文件夹仍存在于工作目录,这里需要删除临时文件夹)
boolean b = ZipExportUtils.deleteExcelPath(file);
throw new BadRequestAlertException("请确认有可导出数据!", ENTITY_NAME, "NoExists");
} else {
// 设置每个Excel的名称
String filename = serverPath + "/" +sheetList.get(0).get(0).get("contractName")+".xls";
ZipExportUtils.getExportResult(sheetList, templatePath, filename);
// 组装数据
Map<String, Object> excelMap = new HashMap<>();
String sheetname = "sheet" + 1;
excelMap.put(sheetname, sheetList);
String encodedfileName = new String(filename.getBytes(), "UTF-8");
// 存放到文件集合中
srcfile.add(new File(encodedfileName));
}
}
// 设置压缩包路径
File zipfile = new File(serverPath + "/" + "单项目业绩" + ".zip");
// 实现将多个excel打包成zip文件
ZipExportUtils.zipFiles(srcfile, zipfile);
// 打印日志
logger.debug("\n"+"打包成功---------------------------" );
// 实现将压缩包写入流中,并删除临时文件中的压缩包及文件
ZipExportUtils.closeFile(response, serverPath, "单项目业绩" + ".zip");
logger.debug("\n"+"压缩成功并删除临时文件---------------------------" );
}
总结
大神们的代码千千万,放在自己系统里就是不好使。所以还是要动脑子,思路逻辑捋清楚,不然真的做无用功