【问题标题】:How to save Excel file to local drive from browser如何从浏览器将 Excel 文件保存到本地驱动器
【发布时间】:2012-09-14 04:59:52
【问题描述】:

我有一个 XPage,它使用 服务器端 javascript 创建 Excel 文件(感谢 Russ Maher)。如果我在浏览器中本地运行 XPage,我知道如何将其保存到 C: 驱动器,但不知道如何在服务器上运行时将其保存到用户计算机,而无需先将其保存到服务器。以下代码用于从服务器的角度保存它。

var fileOut = new java.io.FileOutputStream(directory+fileName);
xl.write(fileOut);
fileOut.close();

有什么想法可以将其引导到用户的驱动器上吗?

【问题讨论】:

    标签: lotus-notes xpages


    【解决方案1】:

    不应将 Excel 工作簿写入 FileOutputStream,而应将其写入 ByteArrayOutputStream:

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    xl.write(outputStream);
    

    您可能需要使用 XAgent 创建输出,然后从 XPage 链接到 XAgent。或许this blog entry by Declan Lynch 结合this answer on how to do it in a servlet 可以引导您走向正确的方向。

    【讨论】:

    • Per 是对的。查看 OpenNTF 上 XSnippets 中的 XAgent sn-p。它提供输出流。因此,与其创建自己的流,不如将其作为参数传递给您的方法。 content-disposition 标头然后可以确定文件名。请记住,用户需要确认保存。还可以查看 Apache POI 以获得更高级的 Excel 输出功能
    • 谢谢,Per,会检查一下。 @stwissel 我正在使用 Apache POI,但我是一个真正的业余爱好者,刚刚采用了 Russ Maher 的实现并对其进行了一些扩展。
    【解决方案2】:

    Paul Calhoun 向我发送了一些示例代码,我对其进行了修改以生成我想要的电子表格。我不知道他做了什么而我没有做,但是,就目前而言,我认为这是解决方案的核心,只是利用 OutputStream 而不是 FileOutputStream 或 ByteArrayOutputStream。

    // The Faces Context global object provides access to the servlet environment via the external content
    var extCont = facesContext.getExternalContext(); 
    // The servlet's response object provides control to the response object
    var pageResponse = extCont.getResponse();
    //Get the output stream to stream binary data
    var pageOutput = pageResponse.getOutputStream();
    
    // Set the content type and headers
    pageResponse.setContentType("application/x-ms-excel");
    pageResponse.setHeader("Cache-Control", "no-cache");
    pageResponse.setHeader("Content-Disposition","inline; filename=" + fileName);
    //Write the output, flush the buffer and close the stream
    wb.write(pageOutput);
    pageOutput.flush();
    pageOutput.close();
    
    //  Terminate the request processing lifecycle.
    facesContext.responseComplete();
    

    如果其他人遇到此问题,我将很乐意提供帮助,并且希望在有人提出要求时,我会更多地了解哪些不同之处有效......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      相关资源
      最近更新 更多