最近在做一个关于数据导出excel的试验,由于数据量较大。总会报OOM。不能完成导出。我用的是jxl,首先尝试一个excel导出多个sheet表,但还是会内存溢出。紧接着,又尝试了一下分批导出。也就是导出多个excel然后进行合并到一个excel,调用了importsheet方法,但最终还是内存溢出,归根结底,主要由于excel添加数据的时候都要new对象,(cell),导致内存不足,最终,采用了压缩文件的方式,发现还是比较合适的。当然有更好的不用压缩的办法,还希望交流一下。
/**
* 将指定文件夹打包成zip
*
* @param folder
* @throws IOException
*/
public static String zipFile(List<String> folder, String path)
throws Exception {
// 目标zip文件
File zipFile = new File(path + "log.zip");
if (zipFile.exists()) {
zipFile.delete();
}
ZipOutputStream zipoutstream = new ZipOutputStream(
new FileOutputStream(zipFile));
// 要压缩的文件处理
for (int i = 0; i < folder.size(); i++) {
File fileExported = new File(folder.get(i));
// File filesInFolder = new File(folder);
// File[] fs = filesInFolder.listFiles();
byte[] buf = null;
// if(fs!=null){
// for (File f : fs) {
zipoutstream.putNextEntry(new ZipEntry(fileExported.getName()));
FileInputStream fileInputStream = new FileInputStream(fileExported);
buf = new byte[8192];
// 定义缓冲流,缓冲区
BufferedInputStream origin = new BufferedInputStream(
fileInputStream, 8192);
// 定义读取的文件字节长短
int len;
while ((len = origin.read(buf, 0, 8192)) != -1) {
zipoutstream.write(buf, 0, len);
}
zipoutstream.flush();
origin.close();
fileInputStream.close();
}
zipoutstream.flush();
zipoutstream.close();
System.out.println("============压缩结束");
return "log.zip";
}