how to return excel in Struts2 result?(如何在 Struts2 结果中返回 excel?)
问题描述
我正在尝试从我的 struts2 操作类返回 Excel 工作表.
I am trying to return an Excel sheet from my struts2 action class.
我不确定我应该使用什么结果类型?有没有人尝试从 struts2 动作类返回一个 excel?
我希望向用户显示打开/保存/取消对话框
I am not sure what result-type should I be using? Has anyone tried to return an excel from struts2 action class?
I would like the user to be presented with open/save/cancel dialog box
推荐答案
Omnipresent 涵盖了您在 struts.xml 中所需要的内容.我也在添加一个带有 Action 的示例:
Omnipresent covered what you need in struts.xml. I'm adding an example with the Action as well:
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.
I'm using the poi model: org.apache.poi.ss.usermodel.
您可以根据需要将xlsx"替换为xls".
You can replace "xlsx" with "xls" if you want.
struts.xml:
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)
(add semicolons and stuff to translate to valid Java)
这篇关于如何在 Struts2 结果中返回 excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Struts2 结果中返回 excel?


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01