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 files
			byte[] 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 file
			int len;
			while ((len = bis.read(buf)) > 0) {
				zipOutputStream.write(buf, 0, len);
			}
			// Complete the entry
			zipOutputStream.closeEntry();
			bis.close();
			is.close();
			// Complete the ZIP file
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

将内存中的ByteArrayOutputStream字节输出流转换成ByteArrayInputStream字节输入流,
然后读入到ZipOutputStream中。

zipOut
  • 12
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
你可以使用Java中的ZipInputStream类来解压缩文件,并使用Apache POI库来解析Excel文件。以下是一个基本的示例代码: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ZipToExcel { public static void main(String[] args) { String zipFilePath = "path/to/zip/file.zip"; String outputFolder = "path/to/output/folder"; try { // 创建输出文件夹 File folder = new File(outputFolder); if (!folder.exists()) { folder.mkdir(); } // 打开ZIP文件 ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath)); // 逐个解压缩文件 ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); // 如果是Excel文件,解析并输出数据 if (fileName.endsWith(".xlsx")) { Workbook workbook = new XSSFWorkbook(zipInputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { System.out.print(cell.toString() + "\t"); } System.out.println(); } // 输出到文件 FileOutputStream fileOutputStream = new FileOutputStream(outputFolder + "/" + fileName); workbook.write(fileOutputStream); fileOutputStream.close(); } zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 此代码将从指定的ZIP文件中解压缩所有.xlsx文件,并将它们解析为Excel文档,然后输出数据并将其写入输出文件夹中的同名文件。你可以根据自己的需要修改代码来提取和处理数据。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值