从GWT客户端下载Excel文件

时间:2019-04-29 14:54:56

标签: servlets gwt apache-poi

我需要在GWT应用程序上从客户端生成一个xls文件(在服务器端使用apache-poi生成)。 我希望当用户单击按钮时,出现一个文件选择器,以允许他保存生成的文件。

首先,我创建了我的servlet:

public class DownloadServlet extends HttpServlet
{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // What I have to insert here?!
    }

    public void getXlsFile()
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Datatypes in Java");
        Object[][] datatypes = { { "Datatype", "Type", "Size(in bytes)" }, { "int", "Primitive", 2 }, { "float", "Primitive", 4 }, { "double", "Primitive", 8 }, { "char", "Primitive", 1 }, { "String", "Non-Primitive", "No fixed size" } };

        int rowNum = 0;

        for (Object[] datatype : datatypes) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (Object field : datatype) {
                Cell cell = row.createCell(colNum++);
                if( field instanceof String ) {
                    cell.setCellValue((String) field);
                }
                else if( field instanceof Integer ) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream("MyFirstExcel.xlsx");
            workbook.write(outputStream);
            workbook.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

现在的问题是:

  • 我该如何填写doGet方法?
  • 如何从客户端调用此servlet?

请注意,客户端不知道xls文件的路径,因为我想在服务器端“即时”创建xls文件。

1 个答案:

答案 0 :(得分:1)

您已经创建了一个servlet并准备好xls文件。您要做的就是将数据推送到HttpServletResponse对象中。

首先,您不需要保存文件。更改getXlsFile()方法以返回XSSFWorkbook,并在最后删除try / catch块。

现在,doGet方法:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HSSFWorkbook workbook = getXlsFile();
    String fileName = "MyFirstExcel.xlsx";

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    resp.setContentType("application/vnd.ms-excel");
    resp.getOutputStream().write(workbook.getBytes());
    resp.getOutputStream().close();
    resp.flushBuffer();

    workbook.close();
}

如何调用服务器?

您需要在web.xml文件中添加 servlet映射

<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>fully.qualified.className</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/path/to/the/servlet</url-pattern>
</servlet-mapping>

简而言之:servlet映射映射 url到servlet类。因此,当您打开/path/to/the/servlet时,将调用fully.qualified.className servlet。