Java servlet trying to output xlsx file but keep getting octet stream

I am trying to create an xlsx file in a servlet and send it to the browser where the user can save or download the file. It currently continues to send the app / octet stream and not the excel file.

What am I doing wrong?

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

      

+3


source to share


1 answer


Set content type and headers before submitting the body. They are called headers for a good reason :-)



+11


source







All Articles