How can I get an Input Stream from HSSFWorkbook Object
My solution is to transfer the HSSFWorkbook to ByteArrayOutputStream first, and then create an InputStream from ByteArrayOutputStream :
HSSFWorkbook wb = ...
// Fill an empty output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
// Close the document
wb.close();
// Create the input stream (do not forget to close the inputStream after use)
InputStream is = new ByteArrayInputStream(baos.toByteArray());
The problem with your question is that you are mixing OutputStreams and InputStreams. An InputStream is something you read from and an OutputStream is something you write to.
This is how I write a POI object to the output stream.
// this part is important to let the browser know what you're sending
response.setContentType("application/vnd.ms-excel");
// the next two lines make the report a downloadable file;
// leave this out if you want IE to show the file in the browser window
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// get the workbook from wherever
HSSFWorkbook wb = getWorkbook();
OutputStream out = response.getOutputStream();
try {
wb.write(out);
}
catch (IOException ioe) {
// if this happens there is probably no way to report the error to the user
if (!response.isCommited()) {
response.setContentType("text/html");
// show response text now
}
}
If you wanted to re-use your existing code you'd have to store the POI data somewhere then turn THAT into an input stream. That'd be easily done by writing it to a ByteArrayOutputStream, then reading those bytes using a ByteArrayInputStream, but I wouldn't recommend it. Your existing method would be more useful as a generic Pipe implementation, where you can pipe the data from an InputStream to and OutputStream, but you don't need it for writing POI objects.
you can create a InputStream from a object.
public InputStream generateApplicationsExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
// Populate a InputStream from the excel object
return new ByteArrayInputStream(excelFile.getBytes());
}