好的.所以最后我完成了所有的障碍,并找到了一种方法来做到这一点.
我意识到我遇到的问题不是创建excel文件,问题是将其发送到客户端,而且也没有在服务器上创建文件或临时文件.
所以这里是如何去做的(我已经从原始代码中删除了细节,以便您可以轻松理解它).
在操作文件中,您首先必须创建HSSFWorkbook对象,将数据放在其上,然后不将其保存到服务器上的磁盘,使用inputstream将其发送到客户端.
动作文件代码:
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;
}
现在在struts-config文件中写一下(注意excelStream& contentDisposition已在动作本身设置,结果类型也是org.apache.struts2.dispatcher.StreamResult):
"application/vnd.ms-excel"
excelStream
contentDisposition
1024
而已.现在,当执行操作时,将提示用户保存或打开文件.
🙂