Apache POI is the most common way to create excel dynamically or statically in our java code. However, most of the times we do it by importing maven dependency for POI and giving the path to excel in FileOutputStream.
Use of FileOutputStreams, doesn't work when the same created excel needs to be transferred over network (encryption is needed --> base64 format).
Chin up!!!
ByteArrayOutputStream is the option to go for it (Create excel using Apache POI, write it in workbook using ByteArrayOutputStream, convert it in byte followed by base64 encoder).
Below is the snippet:
ByteArrayOutputStream b = new ByteArrayOutputStream();
try {
workbook.write(b);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
byte[] bytes = bos.toByteArray();
Base64.encodeBase64String(bytes);
This solution worked for me, As first excel was created using Apache POI then applied above code and converted it to base64, which when decoded over network, encoded file was got opened in a excel application as expected. 😀😀