3

I am trying to generate an Excel spreadsheet from spring application. It is getting generated with a .do extension instead of .xls. But if I rename the downloaded file to .xls, I can see all my content available in Excel. My controller code is below.

    @RequestMapping(value="getReportsList.do")
    public ModelAndView getReports(HttpServletRequest request,
            HttpServletResponse response,
            @ModelAttribute("ordCommand") OrdCommand ordCommand,
        BindingResult errors) throws Exception {

    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
    List<Object[]> recordsArray = null;


    try {

        List<ReportVO> recordsArray = ordService.getDCTrackReports();


        if (null != recordsArray ) {
            //excel formatting code
        }

        response.setHeader("Cache-Control", "public");
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Content-Disposition", "my_report.xls");
        response.setContentType("application/vnd.ms-excel");
    //  ServletOutputStream out = response.getOutputStream()
        if (byteArrayStream != null) {
            response.getOutputStream().write(byteArrayStream.toByteArray());
        }
        response.getOutputStream().flush();
        byteArrayStream.flush();
        byteArrayStream.close();
    } catch (Exception e) {
        e.getMessage();
    }

    return null;

}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
maverick
  • 51
  • 2

2 Answers2

1

Please try to set the Content-Disposition header:

 response.setHeader("Content-Disposition", "inline:filename=\"my_report.xls\"");

The differences between "inline" and "attachment": Content-Disposition:What are the differences between "inline" and "attachment"?

The Content-Disposition Header https://www.rfc-editor.org/rfc/rfc6266

Community
  • 1
  • 1
santc mc
  • 91
  • 4
1

Add filename in Content-Disposition and add make it as attachment and add content type to response with attachment,

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

This will for for sure.

Harshal Patil
  • 6,659
  • 8
  • 41
  • 57