As the title suggest, I need to put some data (which I have got from database) into an excel sheet, and then send it to client side so that user can save , open or cancel th
Okay. So finally I am through with all the roadblocks and have figured out a way to do this.
I realized that the problem I was facing was not in creating the excel file, the problem was sending it to client side, and that too without creating a file or temporary file on the server.
So here is how to go about it (I have ripped off details from my original code so that you can easily understand it).
In the action file you first have to create a HSSFWorkbook object, put data on it and then without saving it to disk on server, send it to client using inputstream.
Action File code :
public String execute(){
setContentDisposition("attachment; filename=\"" + ename + ".xls\"");
try{
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
//////You can repeat this part using for or while to create multiple rows//////
HSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setValue("col0");
row.createCell(1).setValue("col1");
row.createCell(2).setValue("col2");
row.createCell(3).setValue("col3");
.
.
.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//////Now you are ready with the HSSFworkbook object to be sent to client//////
///////////////////////////////////////////////////////////////////////////////
ByteArrayOutputStream baos = new ByteArrayOutputStream();
hwb.write(baos);
excelStream = new ByteArrayInputStream(baos.toByteArray());
///////////////////////////////////////////////////////////////////////////////
////Here HSSFWorkbook object is sent directly to client w/o saving on server///
///////////////////////////////////////////////////////////////////////////////
}catch(Exception e){
System.out.println(e.getMessage());
}
return SUCCESS;
}
Now in the struts-config file just write (note that excelStream & contentDisposition has been set in the action itself also the result-type here is org.apache.struts2.dispatcher.StreamResult):
"application/vnd.ms-excel"
excelStream
contentDisposition
1024
Thats it. Now when the action is executed, the user will be prompted to save or open the file.
:)