我想将多个xssf文件写入zip并下载。我使用以下代码但每次只有一个xssf文件在zip文件夹中。 我正在使用JSF下载zip。
public void downloadData()抛出异常{
FacesContext fc = FacesContext.getCurrentInstance();
setSourceList(new ArrayList<String>());
setTargetList(new ArrayList<String>());
List<String> tempList = dualList.getTarget();
System.out.println(tempList.size());
if (tempList != null && tempList.size() > 0) {
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/zip");
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"Export.zip\"");
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outByteStream);
OutputStream outStream = ec.getResponseOutputStream();
for (int i = 0; i < tempList.size(); i++) {
outByteStream = new ByteArrayOutputStream();
zip = new ZipOutputStream(outByteStream);
// outStream = ec.getResponseOutputStream();
int id = ownerNameIdMap.get(tempList.get(i));
String oName = tempList.get(i);
String fileName = oName + ".xlsx";
if (petList != null && petList.size() > 0) {
petList.clear();
}
workBook = new XSSFWorkbook();
OwnerModel ownerModel = ownerMap.get(id);
ownerFirstName = ownerModel.getFirstName();
ownerLastName = ownerModel.getLastName();
workSheet = workBook.createSheet(ownerLastName + ", " + ownerFirstName);
petList = iOwnerRepository.getActivePetsOfOwner(ownerModel.getId());
petCount = petList.size();
createMasterSheet();
renderSheet(ownerModel);
workBook.write(outByteStream);
addEntry(zip, fileName, outByteStream);
workBook.write(zip);
outStream.write(outByteStream.toByteArray());
outStream.flush();
}
outStream.close();
// zip.closeEntry();
zip.close();
fc.responseComplete();
}
}
public void addEntry(ZipOutputStream zip, String filename, ByteArrayOutputStream os) {
System.out.println(filename);
byte[] bytes = os.toByteArray();
// ZipEntry entry = new ZipEntry(filename);
// Date d = new Date();
// entry.setTime(d.getTime());
try {
((ZipOutputStream) zip).putNextEntry(new ZipEntry(filename));
((ZipOutputStream) zip).write(bytes);
((ZipOutputStream) zip).closeEntry();
} catch (IOException e) {
log.error("Can't read the file !", e);
} catch (ClassCastException cce) {
log.error("Bad format !", cce);
}
}