2

Tengo que enviar un Excel desde el servidor de SpringBoot al cliente en Angular2, El Excel no existe y no se puede crear porque no tengo permisos de escrita, así que habrá que meterlo en un buffer o algo...

El problema que estoy teniendo es que no puedo meter el HSSFWorkbook donde tengo los datos a la respuesta que tengo que mandar al cliente.

 @RequestMapping(method = RequestMethod.GET, path = "/{download}/{data}/{nameFile}", produces = MediaType.APPLICATION_JSON_VALUE)
            public synchronized void download(HttpServletResponse response , @PathVariable("data") Boolean data, @PathVariable("nameFile") String nameFile) {

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
             response.setHeader("Content-disposition", "attachment; filename="+nameFile+"result.xlsx");

             String eyelash = "People";

             try {  
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet(eyelash);

                String[] header = { "Name","Surname","Dni","Age","Tlf" };
                HSSFRow rowhead = sheet.createRow((short) 0);
                HSSFCell cell;
                int cellnum = 0;

                if (data) {
                    int myRowData = 1;
                    HSSFRow row = sheet.createRow((short) myRowData);
                    ArrayList list = mlService.selectAll();

                    for (int i = 0; i < list.size(); i++) {
                        row.createCell(0).setCellValue(list.get(i).getName().substring(0, 4));
                        row.createCell(1).setCellValue(list.get(i).getSurname().substring(4, 6));
                        row.createCell(2).setCellValue(list.get(i).getDni());
                        row.createCell(3).setCellValue(list.get(i).getYear());
                        row.createCell(4).setCellValue(list.get(i).getTlf());

                        myRowData++;
                        row = sheet.createRow((short) myRowData);
                    }
                } 

                final InputStream is = new FileInputStream(workbook) ; //error
                IOUtils.copy(is, response.getOutputStream());
                response.flushBuffer();

            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println(ex.getMessage());
                // deal with error, e.g. response.setStatus(500) to signal an internal server error
            }
    }

Entonces espero una booleana y el tipo de archivo (pueden ser muchos), en este ejemplo he puesto que siempre es el mismo.

Después la respuesta Http donde añado las cabeceras y le digo al navegador que tipo de formato tiene el archivo.

Después construyo el archivo con HSSFWorkbook, la construcción es correcta Y finalmente quiero enviárselo al cliente donde intento meter el woorkbook al file inputStream pero no deja porque no es una archivo o algo de eso y supuestamente cuando lo consiga, se metería en el buffer de la respuesta...

No sé si ando bien encaminado o qué... además de que me da error...

Finalmente el SpringBoot creará el Excel y lo mandará al cliente sin haberlo creado.

Gracias.

1 respuesta 1

1

Se me ocurren los siguientes cambios:

@RequestMapping(method = RequestMethod.GET,
    path = "/download/{data}/{nameFile}",
    produces = MediaType.APPLICATION_JSON_VALUE)
public void download(HttpServletResponse response , @PathVariable("data") Boolean data, @PathVariable("nameFile") String nameFile) {
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment; filename="+nameFile+"result.xlsx");

        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-disposition", "inline; filename=" + nameFile);
        response.setContentLength(excelFileByte.length);

        try {  
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(eyelash);

        String[] header = { "Name","Surname","Dni","Age","Tlf" };
        Row rowhead = sheet.createRow((short) 0);
        Cell cell;
        int cellnum = 0;

        if (data) {
            int myRowData = 1;
            Row row = sheet.createRow((short) myRowData);
            ArrayList list = mlService.selectAll();

            for (int i = 0; i < list.size(); i++) {
                row.createCell(0).setCellValue(list.get(i).getName().substring(0, 4));
                row.createCell(1).setCellValue(list.get(i).getSurname().substring(4, 6));
                row.createCell(2).setCellValue(list.get(i).getDni());
                row.createCell(3).setCellValue(list.get(i).getYear());
                row.createCell(4).setCellValue(list.get(i).getTlf());

                myRowData++;
                row = sheet.createRow((short) myRowData);
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        book.write(baos);
        byte[] excelFileByte = baos.toByteArray();

        ServletOutputStream out = response.getOutputStream();
        out.write(excelFileByte, 0, excelFileByte.length);
        out.flush();
        out.close();

    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println(ex.getMessage());

    }
}

He cambiado de HSSF a XSSF, porque HSSF es el formato de los ficheros XLS (Excel anterior a 2007) y no de los XLSX.

He quitado synchronized porque no veo motivos para añadirlo al método.

Tengo un código muy similar y funciona correctamente. Para descargarlo con Angular te recomiendo crear un enlace en tu página en lugar de usar AJAX: es directo y funciona correctamente, algo como

<a href="mi_aplicacion/download..." class="btn"> Descarga Excel </a>
4
  • pero con el Angular ? ¿ cómo hace la descarga ? y¿ la petición { responseType: 'Blob' }) ? , probaré lo tuyo después del bocata, muchas gracias.
    – EduBw
    el 24 jul. 2018 a las 9:16
  • Puedo descargar el excel si pongo la ruta directamente en el navegador, pero el angular me da un error de SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text
    – EduBw
    el 24 jul. 2018 a las 9:52
  • Como te comento en la respuesta, no uses AJAX, genera un enlace. Si lo descargas con AJAX no tienes un json, es normal que falle. Tienes un Blob que tienes que permitir descargar y es una tarea compleja que preferirás evitar el 24 jul. 2018 a las 9:54
  • Perdona, pero yo no uso ajax, uso Angular, ¿ podrías meterte al chat ?
    – EduBw
    el 24 jul. 2018 a las 9:55

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.