How to return excel to Struts2 result?

I am trying to return an Excel sheet from my struts2 action class.

I'm not sure which type of result should I use? Has anyone tried to return excel from class action struts2?
I would like the user to be presented with an open / save / cancel dialog

+2
source share
2 answers

Everyone knows what you need in struts.xml. I also add an example with 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" } 

I am using the poi model: org.apache.poi.ss.usermodel.

You can replace "xlsx" with "xls" if you want.

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> 

(add semicolons and stuff to translate into valid Java)

+6
source

You can use stream result type

An example would look like this:

 <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> 

excelStream will be the method in your action class, contentLength will be the length of the stream, fileName will be the receiver that will return the file name.

+5
source

Source: https://habr.com/ru/post/1396620/


All Articles