如何在Struts2结果中返回excel?

我试图从我的struts2动作类返回Excel工作表。

我不确定应该使用哪种结果类型? 有没有人试图从struts2动作类返回一个excel?
我希望向用户显示打开/保存/取消对话框

Omnipresent涵盖了struts.xml中您需要的内容。 我也在添加Action的示例:

InputStream excelStream String contentDisposition String documentFormat = "xlsx" String excel() { ServletContext servletContext = ServletActionContext.getServletContext() String filePath = servletContext.getRealPath("/WEB-INF/template/excel/mytemplate.${documentFormat}") File file = new File(filePath) Workbook wb = WorkbookFactory.create(new FileInputStream(file)) Sheet sheet = wb.getSheetAt(0)  ByteArrayOutputStream baos = new ByteArrayOutputStream() wb.write(baos) excelStream = new ByteArrayInputStream(baos.toByteArray()) contentDisposition = "filename=\"myfilename.${documentFormat}\"" return SUCCESS } String getExcelContentType() { return documentFormat == "xlsx" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/vnd.ms-excel" } 

我正在使用poi模型:org.apache.poi.ss.usermodel。

如果需要,可以将“xlsx”替换为“xls”。

struts.xml中:

   ${excelContentType} excelStream contentDisposition 1024   

(添加分号和东西以转换为有效的Java)

您可以使用“ 流结果”类型

示例将如下所示:

  application/vnd.ms-excel excelStream attachment; filename="${fileName}" 1024 ${contentLength}  

excelStream将是你的动作类中的一个方法, contentLength将是流的长度, fileName将是一个getter,它将返回该文件的名称。