如何在Struts2中返回excel结果?

发布于 2024-07-24 07:19:33 字数 122 浏览 3 评论 0原文

我正在尝试从 struts2 操作类返回 Excel 工作表。

我不确定应该使用什么结果类型? 有没有人尝试从 struts2 操作类返回 excel?
我希望向用户显示打开/保存/取消对话框

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

☆獨立☆ 2024-07-31 07:19:33

无所不在的 struts.xml 涵盖了您所需要的内容。 我还添加了一个带有操作的示例:

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 模型: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>

添加分号和其他内容以转换为有效的 Java)

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)

不一样的天空 2024-07-31 07:19:33

您可以使用 Stream Result 类型,

示例如下所示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 将是您的操作类中的一个方法,contentLength 将是流的长度,fileName 将是一个将返回的 getter文件的名称。

You can utilize the Stream Result type

an Example will 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 a method in your action class, contentLength will be length of the stream, fileName will be a getter which will return back the name of the file.

街道布景 2024-07-31 07:19:33

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

JSP

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

Action Method

@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();
        }
    }
}

If you need to dynamically generate an Excel file using POI/HSSF and return in Struts 2,

JSP

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

Action Method

@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();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文