how to return excel in Struts2 result?

后端 未结 3 564
眼角桃花
眼角桃花 2020-12-17 06:31

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

I am not sure what result-type should I be using? Has anyone tried to return an excel from strut

3条回答
  •  死守一世寂寞
    2020-12-17 07:21

    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)
    
    
    
        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'm using the poi model: org.apache.poi.ss.usermodel.

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

    struts.xml:

    
            
                ${excelContentType}
                excelStream
                contentDisposition
                1024
            
        
    

    (add semicolons and stuff to translate to valid Java)

提交回复
热议问题