我正在尝试从我的 struts2 操作类返回一个 Excel 工作表。
我不确定应该使用哪种结果类型?有没有人试过从 struts2 Action 类返回一个 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)
<write to excel file>
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:
<action name="myaction" class="com.example.MyAction" method="excel">
<result type="stream">
<param name="contentType">${excelContentType}</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">contentDisposition</param>
<param name="bufferSize">1024</param>
</result>
</action>
(添加分号和内容以转换为有效的 Java)
关于java - 如何在Struts2结果中返回excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1003892/