Search code examples
export-to-excel

Extension not added on excel generation (APACHE POI)


I am generating an excel sheet using Apache POI in my spring mvc3 project. The file is generated without .xls extension. If I rename the same file with .xls manually the data is generated fine. Here is the snippet of my code::

@RequestMapping(value = "/download/")
    public void downloadMerchantMiniStatement(final HttpServletResponse response,
            @RequestParam(value = "fromDate", required = true) String fromDate,
            @RequestParam(value = "toDate", required = true) String toDate,
            @RequestParam(value = "status", required = false) String status
            ) throws IOException {

        String fileName = STATEMENT_REPORT_" + getDateString(new Date()) + ".xls";
        List<TransactionDTO> transactionDtos = excelService.getTransactionsForExcel(Status, DateUtil.convertStringToDate(fromDate), DateUtil.convertStringToDate(toDate));

        ByteArrayOutputStream excel = getExcelStatement(transactionDtos, fromDate, toDate, status);
        excel.writeTo(response.getOutputStream());
        response.setContentType("application/excel");
        response.setHeader("Expires:", "0");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

Solution

  • Finally got the solution, the code response.setContentType("application/excel"); needed to be replaced with response.setContentType("application/vnd.ms-excel");

    That gives a standard format output.