简体   繁体   中英

How to compress and download a xlsx file using zip in java

I'm creating a xlsx using poi and saving it on fileSystem. I need to download the file on a servlet call and due to memory constraints I did not create a xssf workbook object and used the following code instead :

byte[] buf = new byte[1024];
ServletOutputStream sOut = response.getOutputStream(); 
FileInputStream input = null;
try {
    long length = fileToRead.length(); 
    input = new FileInputStream(fileToRead);

    while ((input != null) && ((length = input.read(buf)) != -1)) {   
          sOut.write(buf, 0, (int) length);  
    }

Where fileToRead is the file present at the file system.

How can I integrate this with How to create a zip file in Java

You could use

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

....
ze = new ZipEntry("xlsData");
zos.putEntry (ze);
// loop
zos.write(buf, 0, (int) length);  

// finally 
zos.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM