Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

java - how to return excel in Struts2 result?

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 struts2 action class?
I would like the user to be presented with open/save/cancel dialog box

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

I'm 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 to valid Java)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...