使用GWT将excel文件从服务器端发送到客户端

时间:2014-11-25 18:33:45

标签: java apache gwt apache-poi

我已经实现了一个允许用户从excel文件中的hashmap保存内容的函数。这样做的代码是服务器端。我希望用户能够将文件保存在他/她自己的计算机上的可选文件位置。

我已经阅读了很多关于堆栈溢出的帖子,其中讨论了如何执行此操作的具体细节。但我看不到整体情况。

我是否应该如何解决这个问题?

我正在使用GWT和apache poi生成excel文件。

2 个答案:

答案 0 :(得分:0)

在服务器端创建servlet,使用ServletOutputStream

- 从GWT Client访问servlet url,当你从客户端调用servlet url时,它会打开一个对话框来保存文件。

见Manik Chand的评论 https://groups.google.com/forum/#!topic/google-web-toolkit/tX5reaOhtew

答案 1 :(得分:0)

您可以这样做:

public class FileServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (request.getRequestURI().contains("/excel")) {

      String id = request.getParameter("id");         
      // Prepare your file for id = 123

      response.setHeader("Content-Disposition", "attachment;filename=myFile.xls");
      response.setContentType("application/vnd.ms-excel");

      OutputStream outputStream = response.getOutputStream();
      // document is byte[] - this is your file.
      outputStream.write(document);
      outputStream.close();
    }
  }
}

然后,您需要在web.xml文件中映射此servlet(例如,到" / file" handler)。最后,您提供了一个指向您的用户的链接,如下所示:

https://mysite.com/file/excel/?id=123

当用户点击此链接时,浏览器会询问此用户保存文件的位置。