Java 批量文件压缩导出并下载到本地示例代码
主要用的是org.apache.tools.zip.ZipOutputStream 这个zip流,这里以Execl为例子。
思路首先把zip流写入到http响应输出流中,再把excel的流写入zip流中(这里可以不用生成文件再打包,只需把execl模板读出写好数据输出到zip流中,并为每次的流设置文件名)
例如:在项目webapp下execl文件中存在1.xls,2.xls,3.xls文件
1.Controller
@RequestMapping(value="/exportAll",method=RequestMethod.GET) publicvoidexportAll()throwsIOException{ try{ HttpServletResponseresponse=this.getResponse(); response.setContentType("application/octet-stream"); StringexeclName="报表"; response.addHeader("Content-Disposition","attachment;filename="+newString(execlName.getBytes(),"iso-8859-1")+".zip"); OutputStreamout=response.getOutputStream(); testService.exportAll(out); }catch(Exceptione){ .... } }
2.Service
importjava.io.OutputStream; importorg.apache.poi.hssf.usermodel.HSSFSheet; importorg.apache.poi.hssf.usermodel.HSSFWorkbook; importorg.apache.tools.zip.ZipEntry; importorg.apache.tools.zip.ZipOutputStream; importjava.io.File; importjava.io.FileInputStream; importjavax.servlet.http.HttpServletRequest; importorg.apache.poi.hssf.usermodel.HSSFCellStyle; importorg.apache.poi.hssf.usermodel.HSSFSheet; importorg.apache.poi.hssf.usermodel.HSSFWorkbook; importorg.apache.poi.poifs.filesystem.POIFSFileSystem; importorg.springframework.web.context.request.RequestContextHolder; importorg.springframework.web.context.request.ServletRequestAttributes; publicbooleanexportAll(OutputStreamout){ ZipOutputStreamzipStream=null; HSSFWorkbookwb=null; try{ Listdatas=testService.getTestData(); zipStream=newZipOutputStream(out);//这里是把zip流输出到httpresponse流中 for(inti=0;i<3;i++){ wb=POIUtil.getWorkbook(i);//获取0,1,2.xls文件 HSSFSheetsheet=wb.getSheetAt(0); testService.setSheet(sheet,datas);//...处理文件内容操作 ZipEntryzipEntry=newZipEntry(newString("文件名XXX".getBytes(),"utf-8")+".xls");//自己命名,这里假设是1,2,3 zipStream.putNextEntry(zipEntry); wb.write(zipStream);//这里就是循环每次把execl写入zip包中 zipStream.flush(); } }catch(Exceptione){ thrownewSysException(ERRORConstants.COMMON_SYSTEM_ERROR,e); }finally{ try{ if(wb!=null){ wb.close(); } if(zipStream!=null){ zipStream.close(); } out.flush(); out.close(); }catch(IOExceptione){ thrownewSysException(ERRORConstants.COMMON_CLOSE_ERROR,e); } } } publicstaticHSSFWorkbookgetWorkbook(Stringbh){ try{ Stringline=File.separator; ServletRequestAttributesaRequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequestrequest=aRequestAttributes==null?null:aRequestAttributes.getRequest(); Stringwebpath=request.getServletContext().getRealPath("/"); Filefile=newFile(webpath+line+"excel"+line+bh+".xls"); POIFSFileSystempoifsFileSystem=newPOIFSFileSystem(newFileInputStream(file)); HSSFWorkbookwb=newHSSFWorkbook(poifsFileSystem); returnwb; }catch(Exceptione){ thrownewSysException(ERRORConstants.COMMON_SYSTEM_ERROR,e); } }
最后的结果生成一个报表.zip,其中包含3个文件1.xls,2.xls,3.xls
总结
以上所述是小编给大家介绍的Java批量文件压缩导出并下载到本地示例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!