3

我正在尝试在 servlet 中创建一个 xlsx 文件并将其发送到用户可以保存或下载文件的浏览器。目前它一直在发送应用程序/八位字节流而不是一个 excel 文件。

我究竟做错了什么?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet = wb.createSheet("Results");
        List<List<TableData>> results = (List<List<TableData>>) request.getSession().getAttribute("results");
        String tableName = (String) request.getSession().getAttribute("tableName");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String filename = tableName+"-"+df.format(date)+".xlsx";

        int rowCounter = 0;

        // Create the rows
        for(List<TableData> l : results) {

            int counter = 0;
            Row row = sheet.createRow(rowCounter);

            for(TableData td : l) {

                Cell cell = row.createCell(counter);

                // if we're on the first row, get the column description, else get the data
                if(rowCounter == 0) {
                    cell.setCellValue(td.getColumnDescription());
                } else {
                    cell.setCellValue(td.getData());
                }
                counter++;
            }
            rowCounter++;
        }

        try {
            OutputStream out = response.getOutputStream();
            wb.write(out);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Expires:", "0"); // eliminates browser caching
            response.setHeader("Content-Disposition", "attachment; filename="+filename);
            out.flush();
            out.close();

        } catch (Exception e) {
            LOG.debug(e.getStackTrace().toString());
        } 
    }
4

1 回答 1

11

在发送正文之前设置内容类型和标题。他们被称为标题是有充分理由的:-)

于 2013-01-21T22:12:50.077 回答