Skip to content
Advertisement

Protect a SXSSFWorkbook (Excel) and convert it to a byte array

I am working on a Java function which is expected to return a protected Excel file (xlsx) in byte array.

public byte[] genProtectedExcel() {
    SXSSFWorkbook workbook = new SXSSFWorkbook();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    //Code of cells fill in...

    //Should be code of workbook encryption...

    workbook.write(baos);
    return baos.toByteArray();
}

I found a solution which used the Encryption support of Apache POI: How to Protect Excel Workbook Via SXSSF?

POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);

Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");

InputStream is = <open the SXSSF workbook as stream>
OutputStream os = enc.getDataStream(fs);
IOUtils.copy(is, os);

However, OutputStream cannot be cast into ByteArrayOutputStream. I tried to find a way to convert the OutputStream into ByteArray but all failed. Is there anyway to create a protect excel byte array?

Advertisement

Answer

ByteArrayOutputStream baos = new ByteArrayOutputStream();

fs.writeFilesystem(baos );

return baos.toByteArray();

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement