好的。所以最后,我克服了所有障碍,并找到了解决方法。
我意识到我面临的问题不是创建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):
<action name="actionName" > <result type="stream"> <param name="contentType">"application/vnd.ms-excel"</param> <param name="inputName">excelStream</param> <param name="contentDisposition">contentDisposition</param> <param name="bufferSize">1024</param> </result> </action>
而已。现在,当执行操作时,将提示用户保存或打开文件。
:)



