JuanmaV7
JuanmaV7

Reputation: 23

When I download Excel from a folder with java I get this error " the format and extension of the .xls file do not match. The file may be damaged"

as the title says, when I download an excel sheet from a folder I get this message

This is my code

RequestMapping(value = "/descargar-datos-entrada/{idSimulacion}", method = RequestMethod.GET)
    public void descargarDatosEntrada(@PathVariable("idSimulacion") String idSimulacion, HttpServletResponse response)
            throws IOException {
        Properties properties = new Properties();
        properties = Util.getProperties("mongo");
        FileInputStream inputStream = null;
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=Hoja-Resultados-Descarga.xls");

        try {

            Simulacion simulacion = simulacionService.finById(idSimulacion);
            inputStream = new FileInputStream(
                    properties.getProperty("ruta.copia.resultados.excel") + idSimulacion + ".xls");

            int c;
            while ((c = inputStream.read()) != -1) {
                response.getWriter().write(c);
            }

        } catch (SimulacionException | IOException e) {
            Util.autoLogError(e);
        } finally {
            if (inputStream != null)
                inputStream.close();
            response.getWriter().close();
        }

    }

and the result .xls file would be as follows:

enter image description here

I would appreciate some help or advice, Thanks in advance, it is my first question so excuse me if I didn't ask it correctly.

Upvotes: 1

Views: 868

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109532

Do binary output with getOutputStream, not text output getWriter:

        Path path = Paths.get(properties.getProperty("ruta.copia.resultados.excel")
                    + idSimulacion + ".xls");
        Files.copy(path, response.getOutputStream());

Upvotes: 3

Related Questions