Java后台生成多个Excel并用Zip打包后(可以将excel文件放置到不同的目录)下载
有时候会遇到需要在后台批量生成Excel并导出的应用场景,为了方便导出下载,通常会采用Zip打包成一个文件然后下载导出的方式实现。
1.导出Excel
之前写过一篇 POI 通用导出Excel(.xls,.xlsx),
所以此处不会再重复写导出Excel的方法,大家可以根据需要改写这个方法以适用自己的需求。
/*** 导出Excel 2007 OOXML (.xlsx)格式* @param title 标题行(可作为文件名)* @param headMap 属性-列头* @param jsonArray 数据集* @param datePattern 日期格式,传null值则默认 年月日* @param colWidth 列宽 默认 至少17个字节* @param out 输出流*/public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) ;
导出Excel方法的定义如上所示,headMap表示表格列头(当然可以用JSONObject替换),该方法最后将生成的Excel以输出流的方式存在内存当中。
在调用该方法时如果声明一个FileOutputStream并传入该方法,最后就以本地文件的方式保存excel;如果传入的是ServletOutputStream则可以返回给浏览器下载;如果传入的是ByteArrayOutputStream则以字节流的形式保存在内存中。
2.ZIP打包多个文件
zip打包多个文件的代码框架如下:
FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
for all files
{ZipEntry ze = new ZipEntry(filename);// file.getName();zout.putNextEntry(ze);send data to zout;zout.closeEntry();
}
zout.close();
如果使用上面的循环文件列表的方式来打包到zip中,意味着生成的多个excel文件需要先保存为文件然后在使用文件IO流来读取文件,这样效率会很低且耗时长。所以可以将生成的excel文件以字节流的形式ByteArrayOutputStream保存在内存中,每生成一个就将它压缩到ZipOutputStream 流中,这样不经过IO读写速度会很快。
下面是zip打包单个excel文件的代码
/*** 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之* @param zipOutputStream zip文件的输出流* @param excelOutputStream excel文件的输出流* @param excelFilename 文件名可以带目录,例如 TestDir/test1.xlsx*/public static void compressFileToZipStream(ZipOutputStream zipOutputStream, ByteArrayOutputStream excelOutputStream,String excelFilename) {byte[] buf = new byte[1024];try {// Compress the filesbyte[] content = excelOutputStream.toByteArray();ByteArrayInputStream is = new ByteArrayInputStream(content);BufferedInputStream bis = new BufferedInputStream(is);// Add ZIP entry to output stream.zipOutputStream.putNextEntry(new ZipEntry(excelFilename));// Transfer bytes from the file to the ZIP fileint len;while ((len = bis.read(buf)) > 0) {zipOutputStream.write(buf, 0, len);}// Complete the entryzipOutputStream.closeEntry();bis.close();is.close();// Complete the ZIP file} catch (IOException e) {e.printStackTrace();}}
将内存中的ByteArrayOutputStream字节输出流转换成ByteArrayInputStream字节输入流,
然后读入到ZipOutputStream中。
zipOutputStream.putNextEntry(new ZipEntry(excelFilename));
此方法的excelFilename参数很有意思,如果需要目录可以传入例如 ”TestDir/test1.xlsx“,那么会在zip中生成TestDir目录并且将生成的test1.xlsx文件会放置到TestDir目录下。这样便实现了生成的文件按目录存放。
3.完整示例
完整的代码如下:
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class ExcelUtil{public static String NO_DEFINE = "no_define";//未定义的字段public static String DEFAULT_DATE_PATTERN="yyyy年MM月dd日";//默认日期格式public static int DEFAULT_COLOUMN_WIDTH = 17;/*** 导出Excel 2007 OOXML (.xlsx)格式* @param title 标题行* @param headMap 属性-列头* @param jsonArray 数据集* @param datePattern 日期格式,传null值则默认 年月日* @param colWidth 列宽 默认 至少17个字节* @param out 输出流*/public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;// 声明一个工作薄SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存workbook.setCompressTempFiles(true);//表头样式CellStyle titleStyle = workbook.createCellStyle();titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);Font titleFont = workbook.createFont();titleFont.setFontHeightInPoints((short) 20);titleFont.setBoldweight((short) 700);titleStyle.setFont(titleFont);// 列头样式CellStyle headerStyle = workbook.createCellStyle();headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);Font headerFont = workbook.createFont();headerFont.setFontHeightInPoints((short) 12);headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);headerStyle.setFont(headerFont);// 单元格样式CellStyle cellStyle = workbook.createCellStyle();cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);Font cellFont = workbook.createFont();cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);cellStyle.setFont(cellFont);// 生成一个(带标题)表格SXSSFSheet sheet = workbook.createSheet();//设置列宽int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数int[] arrColWidth = new int[headMap.size()];// 产生表格标题行,以及设置列宽String[] properties = new String[headMap.size()];String[] headers = new String[headMap.size()];int ii = 0;for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext();) {String fieldName = iter.next();properties[ii] = fieldName;headers[ii] = headMap.get(fieldName);int bytes = fieldName.getBytes().length;arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;sheet.setColumnWidth(ii,arrColWidth[ii]*256);ii++;}// 遍历集合数据,产生数据行int rowIndex = 0;for (Object obj : jsonArray) {if(rowIndex == 65535 || rowIndex == 0){if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示SXSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0titleRow.createCell(0).setCellValue(title);titleRow.getCell(0).setCellStyle(titleStyle);sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));SXSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1for(int i=0;i<headers.length;i++){headerRow.createCell(i).setCellValue(headers[i]);headerRow.getCell(i).setCellStyle(headerStyle);}rowIndex = 2;//数据内容从 rowIndex=2开始}JSONObject jo = (JSONObject) JSONObject.toJSON(obj);SXSSFRow dataRow = sheet.createRow(rowIndex);for (int i = 0; i < properties.length; i++){SXSSFCell newCell = dataRow.createCell(i);Object o = jo.get(properties[i]);String cellValue = ""; if(o==null) cellValue = "";else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);/*else if(o instanceof Float || o instanceof Double) {double d = (double) o;if(d%1==0) cellValue=o.toString();else cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();}*/else cellValue = o.toString();newCell.setCellValue(cellValue);newCell.setCellStyle(cellStyle);}rowIndex++;}// 自动调整宽度/*for (int i = 0; i < headers.length; i++) {sheet.autoSizeColumn(i);}*/try {workbook.write(out);workbook.close();workbook.dispose();} catch (IOException e) {e.printStackTrace();}}/*** 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之* @param zipOutputStream zip文件的输出流* @param excelOutputStream excel文件的输出流* @param excelFilename 文件名可以带目录,例如 TestDir/test1.xlsx*/public static void compressFileToZipStream(ZipOutputStream zipOutputStream, ByteArrayOutputStream excelOutputStream,String excelFilename) {byte[] buf = new byte[1024];try {// Compress the filesbyte[] content = excelOutputStream.toByteArray();ByteArrayInputStream is = new ByteArrayInputStream(content);BufferedInputStream bis = new BufferedInputStream(is);// Add ZIP entry to output stream.zipOutputStream.putNextEntry(new ZipEntry(excelFilename));// Transfer bytes from the file to the ZIP fileint len;while ((len = bis.read(buf)) > 0) {zipOutputStream.write(buf, 0, len);}// Complete the entry//excelOutputStream.close();//关闭excel输出流zipOutputStream.closeEntry();bis.close();is.close();// Complete the ZIP file} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException {int count = 100;JSONArray ja = new JSONArray();for(int i=0;i<count;i++){Student s = new Student();s.setName("POI"+i);s.setAge(i);s.setBirthday(new Date());s.setHeight(i);s.setWeight(i);s.setSex(i/2==0?false:true);ja.add(s);}Map<String,String> headMap = new LinkedHashMap<String,String>();headMap.put("name","姓名");headMap.put("age","年龄");headMap.put("birthday","生日");headMap.put("height","身高");headMap.put("weight","体重");headMap.put("sex","性别");//导出zipOutputStream outXlsx = new FileOutputStream("E://test.zip");ZipOutputStream zipOutputStream = new ZipOutputStream(outXlsx);for(int i=1;i<6;i++) {String dir = i%2==0?"dirA":"dirB";ByteArrayOutputStream baos = new ByteArrayOutputStream();ExcelUtil.exportExcelX(title,headMap,ja,null,0,baos);ExcelUtil.compressFileToZipStream(zipOutputStream, baos, dir+"/test"+i+".xlsx");baos.close();} zipOutputStream.flush();zipOutputStream.close();outXlsx.close();System.out.println("导出zip完成");}
}
class Student {private String name;private int age;private Date birthday;private float height;private double weight;private boolean sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public float getHeight() {return height;}public void setHeight(float height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public boolean isSex() {return sex;}public void setSex(boolean sex) {this.sex = sex;}public void setAge(Integer age) {this.age = age;}
}
要在Web端下载,只需将FileOutputStream替换为ServletOutputStream
public void exprotZip(HttpServletResponse response)ServletOutputStream sos = response.getOutputStream();ZipOutputStream zipOutputStream= new ZipOutputStream(sos);String zipname="test.zip";response.reset();response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename="+ new String((zipname).getBytes(), "iso-8859-1"));for(int i=1;i<6;i++) {String dir = i%2==0?"dirA":"dirB";ByteArrayOutputStream baos = new ByteArrayOutputStream();ExcelUtil.exportExcelX(title,headMap,ja,null,0,baos);ExcelUtil.compressFileToZipStream(zipOutputStream, baos, dir+"/test"+i+".xlsx");baos.close();} zipOutputStream.flush();zipOutputStream.close();sos .close();System.out.println("导出zip完成");
}
上面的难点主要在于字节流的操作,相信弄明白了示例代码,会对流具有更深刻的理解。
《道德经》第九章:
持而盈之,不如其已;揣而锐之,不可长保。金玉满堂,莫之能守;富贵而骄,自遗其咎。功成身退,天之道也。
译文:执持盈满,不如适时停止;显露锋芒,锐势难以保持长久。金玉满堂,无法守藏;如果富贵到了骄横的程度,那是自己留下了祸根。一件事情做的圆满了,就要含藏收敛,这是符合自然规律的道理。
Java后台生成多个Excel并用Zip打包后(可以将excel文件放置到不同的目录)下载
有时候会遇到需要在后台批量生成Excel并导出的应用场景,为了方便导出下载,通常会采用Zip打包成一个文件然后下载导出的方式实现。
1.导出Excel
之前写过一篇 POI 通用导出Excel(.xls,.xlsx),
所以此处不会再重复写导出Excel的方法,大家可以根据需要改写这个方法以适用自己的需求。
/*** 导出Excel 2007 OOXML (.xlsx)格式* @param title 标题行(可作为文件名)* @param headMap 属性-列头* @param jsonArray 数据集* @param datePattern 日期格式,传null值则默认 年月日* @param colWidth 列宽 默认 至少17个字节* @param out 输出流*/public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) ;
导出Excel方法的定义如上所示,headMap表示表格列头(当然可以用JSONObject替换),该方法最后将生成的Excel以输出流的方式存在内存当中。
在调用该方法时如果声明一个FileOutputStream并传入该方法,最后就以本地文件的方式保存excel;如果传入的是ServletOutputStream则可以返回给浏览器下载;如果传入的是ByteArrayOutputStream则以字节流的形式保存在内存中。
2.ZIP打包多个文件
zip打包多个文件的代码框架如下:
FileOutputStream fout = new FileOutputStream("test.zip");
ZipOutputStream zout = new ZipOutputStream(fout);
for all files
{ZipEntry ze = new ZipEntry(filename);// file.getName();zout.putNextEntry(ze);send data to zout;zout.closeEntry();
}
zout.close();
如果使用上面的循环文件列表的方式来打包到zip中,意味着生成的多个excel文件需要先保存为文件然后在使用文件IO流来读取文件,这样效率会很低且耗时长。所以可以将生成的excel文件以字节流的形式ByteArrayOutputStream保存在内存中,每生成一个就将它压缩到ZipOutputStream 流中,这样不经过IO读写速度会很快。
下面是zip打包单个excel文件的代码
/*** 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之* @param zipOutputStream zip文件的输出流* @param excelOutputStream excel文件的输出流* @param excelFilename 文件名可以带目录,例如 TestDir/test1.xlsx*/public static void compressFileToZipStream(ZipOutputStream zipOutputStream, ByteArrayOutputStream excelOutputStream,String excelFilename) {byte[] buf = new byte[1024];try {// Compress the filesbyte[] content = excelOutputStream.toByteArray();ByteArrayInputStream is = new ByteArrayInputStream(content);BufferedInputStream bis = new BufferedInputStream(is);// Add ZIP entry to output stream.zipOutputStream.putNextEntry(new ZipEntry(excelFilename));// Transfer bytes from the file to the ZIP fileint len;while ((len = bis.read(buf)) > 0) {zipOutputStream.write(buf, 0, len);}// Complete the entryzipOutputStream.closeEntry();bis.close();is.close();// Complete the ZIP file} catch (IOException e) {e.printStackTrace();}}
将内存中的ByteArrayOutputStream字节输出流转换成ByteArrayInputStream字节输入流,
然后读入到ZipOutputStream中。
zipOutputStream.putNextEntry(new ZipEntry(excelFilename));
此方法的excelFilename参数很有意思,如果需要目录可以传入例如 ”TestDir/test1.xlsx“,那么会在zip中生成TestDir目录并且将生成的test1.xlsx文件会放置到TestDir目录下。这样便实现了生成的文件按目录存放。
3.完整示例
完整的代码如下:
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class ExcelUtil{public static String NO_DEFINE = "no_define";//未定义的字段public static String DEFAULT_DATE_PATTERN="yyyy年MM月dd日";//默认日期格式public static int DEFAULT_COLOUMN_WIDTH = 17;/*** 导出Excel 2007 OOXML (.xlsx)格式* @param title 标题行* @param headMap 属性-列头* @param jsonArray 数据集* @param datePattern 日期格式,传null值则默认 年月日* @param colWidth 列宽 默认 至少17个字节* @param out 输出流*/public static void exportExcelX(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;// 声明一个工作薄SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存workbook.setCompressTempFiles(true);//表头样式CellStyle titleStyle = workbook.createCellStyle();titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);Font titleFont = workbook.createFont();titleFont.setFontHeightInPoints((short) 20);titleFont.setBoldweight((short) 700);titleStyle.setFont(titleFont);// 列头样式CellStyle headerStyle = workbook.createCellStyle();headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);Font headerFont = workbook.createFont();headerFont.setFontHeightInPoints((short) 12);headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);headerStyle.setFont(headerFont);// 单元格样式CellStyle cellStyle = workbook.createCellStyle();cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);Font cellFont = workbook.createFont();cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);cellStyle.setFont(cellFont);// 生成一个(带标题)表格SXSSFSheet sheet = workbook.createSheet();//设置列宽int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数int[] arrColWidth = new int[headMap.size()];// 产生表格标题行,以及设置列宽String[] properties = new String[headMap.size()];String[] headers = new String[headMap.size()];int ii = 0;for (Iterator<String> iter = headMap.keySet().iterator(); iter.hasNext();) {String fieldName = iter.next();properties[ii] = fieldName;headers[ii] = headMap.get(fieldName);int bytes = fieldName.getBytes().length;arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;sheet.setColumnWidth(ii,arrColWidth[ii]*256);ii++;}// 遍历集合数据,产生数据行int rowIndex = 0;for (Object obj : jsonArray) {if(rowIndex == 65535 || rowIndex == 0){if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了,则在第二页显示SXSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0titleRow.createCell(0).setCellValue(title);titleRow.getCell(0).setCellStyle(titleStyle);sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));SXSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1for(int i=0;i<headers.length;i++){headerRow.createCell(i).setCellValue(headers[i]);headerRow.getCell(i).setCellStyle(headerStyle);}rowIndex = 2;//数据内容从 rowIndex=2开始}JSONObject jo = (JSONObject) JSONObject.toJSON(obj);SXSSFRow dataRow = sheet.createRow(rowIndex);for (int i = 0; i < properties.length; i++){SXSSFCell newCell = dataRow.createCell(i);Object o = jo.get(properties[i]);String cellValue = ""; if(o==null) cellValue = "";else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);/*else if(o instanceof Float || o instanceof Double) {double d = (double) o;if(d%1==0) cellValue=o.toString();else cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();}*/else cellValue = o.toString();newCell.setCellValue(cellValue);newCell.setCellStyle(cellStyle);}rowIndex++;}// 自动调整宽度/*for (int i = 0; i < headers.length; i++) {sheet.autoSizeColumn(i);}*/try {workbook.write(out);workbook.close();workbook.dispose();} catch (IOException e) {e.printStackTrace();}}/*** 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之* @param zipOutputStream zip文件的输出流* @param excelOutputStream excel文件的输出流* @param excelFilename 文件名可以带目录,例如 TestDir/test1.xlsx*/public static void compressFileToZipStream(ZipOutputStream zipOutputStream, ByteArrayOutputStream excelOutputStream,String excelFilename) {byte[] buf = new byte[1024];try {// Compress the filesbyte[] content = excelOutputStream.toByteArray();ByteArrayInputStream is = new ByteArrayInputStream(content);BufferedInputStream bis = new BufferedInputStream(is);// Add ZIP entry to output stream.zipOutputStream.putNextEntry(new ZipEntry(excelFilename));// Transfer bytes from the file to the ZIP fileint len;while ((len = bis.read(buf)) > 0) {zipOutputStream.write(buf, 0, len);}// Complete the entry//excelOutputStream.close();//关闭excel输出流zipOutputStream.closeEntry();bis.close();is.close();// Complete the ZIP file} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException {int count = 100;JSONArray ja = new JSONArray();for(int i=0;i<count;i++){Student s = new Student();s.setName("POI"+i);s.setAge(i);s.setBirthday(new Date());s.setHeight(i);s.setWeight(i);s.setSex(i/2==0?false:true);ja.add(s);}Map<String,String> headMap = new LinkedHashMap<String,String>();headMap.put("name","姓名");headMap.put("age","年龄");headMap.put("birthday","生日");headMap.put("height","身高");headMap.put("weight","体重");headMap.put("sex","性别");//导出zipOutputStream outXlsx = new FileOutputStream("E://test.zip");ZipOutputStream zipOutputStream = new ZipOutputStream(outXlsx);for(int i=1;i<6;i++) {String dir = i%2==0?"dirA":"dirB";ByteArrayOutputStream baos = new ByteArrayOutputStream();ExcelUtil.exportExcelX(title,headMap,ja,null,0,baos);ExcelUtil.compressFileToZipStream(zipOutputStream, baos, dir+"/test"+i+".xlsx");baos.close();} zipOutputStream.flush();zipOutputStream.close();outXlsx.close();System.out.println("导出zip完成");}
}
class Student {private String name;private int age;private Date birthday;private float height;private double weight;private boolean sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public float getHeight() {return height;}public void setHeight(float height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public boolean isSex() {return sex;}public void setSex(boolean sex) {this.sex = sex;}public void setAge(Integer age) {this.age = age;}
}
要在Web端下载,只需将FileOutputStream替换为ServletOutputStream
public void exprotZip(HttpServletResponse response)ServletOutputStream sos = response.getOutputStream();ZipOutputStream zipOutputStream= new ZipOutputStream(sos);String zipname="test.zip";response.reset();response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename="+ new String((zipname).getBytes(), "iso-8859-1"));for(int i=1;i<6;i++) {String dir = i%2==0?"dirA":"dirB";ByteArrayOutputStream baos = new ByteArrayOutputStream();ExcelUtil.exportExcelX(title,headMap,ja,null,0,baos);ExcelUtil.compressFileToZipStream(zipOutputStream, baos, dir+"/test"+i+".xlsx");baos.close();} zipOutputStream.flush();zipOutputStream.close();sos .close();System.out.println("导出zip完成");
}
上面的难点主要在于字节流的操作,相信弄明白了示例代码,会对流具有更深刻的理解。
《道德经》第九章:
持而盈之,不如其已;揣而锐之,不可长保。金玉满堂,莫之能守;富贵而骄,自遗其咎。功成身退,天之道也。
译文:执持盈满,不如适时停止;显露锋芒,锐势难以保持长久。金玉满堂,无法守藏;如果富贵到了骄横的程度,那是自己留下了祸根。一件事情做的圆满了,就要含藏收敛,这是符合自然规律的道理。