繁体   English   中英

如何在 Struts2 结果中返回 excel?

[英]how to return excel in Struts2 result?

我正在尝试从我的 struts2 操作 class 返回一张 Excel 表。

我不确定应该使用哪种结果类型? 有没有人试图从 struts2 行动 class 返回 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"
}

我正在使用 poi model: org.apache.poi.ss.usermodel。

如果需要,您可以将“xlsx”替换为“xls”。

支柱.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)

您可以使用Stream 结果类型

一个示例将如下所示:

<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将是您操作中的一个方法 class, contentLength将是 stream 的长度, fileName将是一个返回文件名的 getter。

如果需要在Struts 2中使用POI/HSSF动态生成一个Excel文件并返回,

JSP

<s:url action="DownloadExcel.action" var="downloadUrl">
</s:url>
<s:a href="%{downloadUrl}">Click to Download</s:a>

动作方法

@Action(value = "DownloadExcel")
public void download() throws Exception {
    
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    
    String filename = "report.xlsx"; // or any other filename strategy
    String mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    String characterEncoding = response.getCharacterEncoding();
    if (characterEncoding != null) {
        mimeType += "; charset=" + characterEncoding;
    }
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + filename);

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.getSheetAt(0);
    // Fill out workbook as necessary... (simple example)
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell(0);
    cell.setCellValue("test");
    //...

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        workbook.write(out);
        workbook.close();
    } catch (IOException e) {
        log.error("Failed to write into response - fileName=" + filename + ", mimeType=" + mimeType, e);
    }
    finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM