Java 导出Zip文件

利用ExcelWriter生成多个excel文件,把文件最终压缩成zip文件,在页面上下载

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

@RequestMapping("/export")
public void exportExcels(String val,String xn, HttpServletRequest request,
HttpServletResponse response)throws Exception {
List<String> filePaths = new ArrayList<>();
List<File> fileList = new ArrayList<File>();

String tmpFileName = xn+"-填报表.zip";
String strZipPath = FilePath + tmpFileName;

HttpSession session = request.getSession();
User user = SessionUtil.getCurrentUser(session);
OutputStream out = null;
ExcelWriter writer = null;
String a[]=val.split(",");
for(String tmpstr : a){
Form form = formService.getById(tmpstr);
try {

Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("sheet1");
List<List<String>> head = Lists.newArrayList();
Role role = SessionUtil.getCurrentRole(session);
List<String> fieldList=new ArrayList<String>();
fieldList=seeService.findFieldList(form.getYwm(),user.getId());
Boolean isAdmin=false;
if((role != null && role.getId().equals("1098034444456992769")) ){
isAdmin=true;
JSONArray jsonArray = JSON.parseArray(form.getDbs());
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
String label = jsonObject.getString("label");
List<String> headCoulumn = Lists.newArrayList();
headCoulumn.add(label);
head.add(headCoulumn);
}
}else{
isAdmin=false;
if(fieldList.size()>0){
for(String label:fieldList){
List<String> headCoulumn = Lists.newArrayList();
String tmp=seeService.findFieldName(tmpstr,user.getId(),label);
if(StringUtils.isNotEmpty(tmp)){
headCoulumn.add(tmp);
}else{
headCoulumn.add(label);
}
head.add(headCoulumn);
}
}
}
List<String> headCoulumn = Lists.newArrayList();
headCoulumn.add("日期");
head.add(headCoulumn);
Table table = new Table(1);
table.setHead(head);
// 获取数据
List<List<String>> data = formService.getDataByTableAndUser(form, user,fieldList,isAdmin,xn);
String filename = FilePath + form.getYwm() + ".xlsx";
// 将文件路径保存
fileList.add(creatFile(filename));
filePaths.add(filename);
File file = new File(filename);
out=new FileOutputStream(file);
//out = response.getOutputStream(filename);
writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
writer.write0(data, sheet1, table);
writer.finish();
}catch (Exception e) {
e.printStackTrace();
}
}
try{
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(strZipPath));

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);
zout.putNextEntry(new ZipEntry(file.getName()));
// 设置压缩文件内的字符编码,不然会变成乱码
//zout.setEncoding("UTF-8");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
zout.write(buffer, 0, len);
}
zout.closeEntry();
fis.close();
}
out.close();
// 下载zip文件
downFile(response, tmpFileName, filePaths);

} catch (Exception e) {
e.printStackTrace();
deleteFile(filePaths);
}
}
private File creatFile(String filePath) {
File file = new File(filePath);
return file;
}
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);
}
}
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;
}

原文地址:https://www.cnblogs.com/foreverstudy/p/13954717.html