我试图从我的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)
<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"
}
Run Code Online (Sandbox Code Playgroud)
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
(添加分号和东西以转换为有效的Java)
您可以使用" 流结果"类型
示例将如下所示:
<result name="excel" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">attachment; filename="${fileName}"</param>
<param name="bufferSize">1024</param>
<param name="contentLength">${contentLength}</param>
</result>
Run Code Online (Sandbox Code Playgroud)
excelStream将是你的动作类中的一个方法,contentLength将是流的长度,fileName将是一个将返回文件名的getter.
| 归档时间: |
|
| 查看次数: |
15932 次 |
| 最近记录: |