Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Pablo Videla en 4 Noviembre 2011, 16:50 pm



Título: Problema al crear excel [SOLUCIONADO]
Publicado por: Pablo Videla en 4 Noviembre 2011, 16:50 pm
Estimados, tengo una aplicación que hice y quiero exportar a excel a partir de un arraylist, la cosa es que me crea el excel, lo bajo me abre con errores, se reinicia el office y automaticamente me lo repara y me lo abre bien, pero la cosa es que quiero que abra sin errores, adjunto metodo


Código
  1.  
  2.  
  3.    public void postProcessXLS() {
  4.        if (movimientos == null) {
  5.            cargaTablaDinamica();
  6.        }
  7.        System.out.println("Entre al metodo postProcess");
  8.  
  9.        //  HSSFWorkbook wb = (HSSFWorkbook) document;
  10.        HSSFWorkbook wb = new HSSFWorkbook();
  11.        HSSFSheet sheet = wb.createSheet("Movimientos");
  12.        // wb.setSheetName(0, "Ejemplo"); //Asignamos nombre a la hoja de calculo
  13.  
  14.     //   HSSFRow header = sheet.createRow(0);
  15.        HSSFRow fila = null;
  16.  
  17.  
  18.  
  19.        //HSSFRow fila = sheet.getRow(1);
  20.       /* Llenar las cosas*/
  21.        for (int i = 0; i < movimientos.size(); i++) {
  22.            fila = sheet.createRow(i);
  23.  
  24.            for (int j = 0; j < 5; j++) {
  25.                fila.createCell(j);
  26.  
  27.            }
  28.  
  29.         /*   fila.getCell(0).setCellValue("Fecha");
  30.             fila.getCell(1).setCellValue("Descripcion");
  31.             fila.getCell(2).setCellValue("Serie");
  32.             fila.getCell(3).setCellValue("Monto");
  33.             fila.getCell(4).setCellValue("Saldo");*/
  34.  
  35.            fila.getCell(0).setCellValue(movimientos.get(i).getFecha().toLocaleString());
  36.  
  37.            fila.getCell(1).setCellValue(movimientos.get(i).getDescripcion());
  38.            fila.getCell(2).setCellValue(movimientos.get(i).getSerie());
  39.            fila.getCell(3).setCellValue((double)movimientos.get(i).getMonto());
  40.            fila.getCell(4).setCellValue((double)movimientos.get(i).getSaldo());
  41.  
  42.        }
  43.  
  44.  
  45. /*
  46.         HSSFCellStyle cellStyle = wb.createCellStyle(); //estilo para la primera fila
  47.         HSSFCellStyle estilo = wb.createCellStyle(); // otro estilo para la segunda fila
  48.         HSSFCellStyle estilo2 = wb.createCellStyle();
  49.  
  50.  
  51.         cellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);// color Naranjo
  52.         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  53.  
  54.         estilo.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);//estilo para la segunda fila
  55.         estilo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  56.  
  57.         estilo2.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
  58.         estilo2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);*/
  59.        System.out.println("El documento pesa : " + wb.getBytes().length);
  60.  
  61.        try {
  62.            FacesContext facesContext = FacesContext.getCurrentInstance();
  63.            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
  64.            //  response.resetBuffer();
  65.  
  66.            response.setContentLength(wb.getBytes().length);
  67.            response.setContentType("application/vnd.ms-excel");
  68.  
  69.  
  70.  
  71.            //     System.out.println("RespuestA ? : " + response.getOutputStream().toString());
  72.            //      ServletOutputStream out = response.getOutputStream();
  73.  
  74.            ServletOutputStream out = response.getOutputStream();
  75.  
  76.            out.write(wb.getBytes());
  77.       //     out.flush();
  78.            out.close();
  79.            //   baosPDF.flush();
  80.            //  baosPDF.close();
  81.            facesContext.responseComplete();
  82.        } catch (Exception e) {
  83.            System.out.println("Error : " + e.getMessage());
  84.            e.printStackTrace();
  85.        }
  86.        // estilo2.setFont(HSSFFont.);
  87.  
  88.        // Este ciclo pintara todas las celdas de la fila 1
  89.  /*      for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
  90.         //header.getPhysicalNumberOfCells obtiene el numero de celdas de la fila
  91.         HSSFCell cell = header.getCell(i);
  92.        
  93.         cell.setCellStyle(cellStyle);//le asigna el estilo a cada celda de la primera fila
  94.         sheet.autoSizeColumn((short) i); // Deja las columnas en un tamaño que se vea todo bien.
  95.         System.out.println("Numero : " + i);//Cantidad de celdas rellenadas
  96.         }
  97.        
  98.        
  99.         // pruebas con las columnas
  100.         // Pintara toda la columna 3 de todas las filas.
  101.         for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
  102.        
  103.         HSSFRow fila = sheet.getRow(i);
  104.         HSSFCell cell = fila.getCell(2);
  105.         cell.setCellStyle(estilo2);
  106.        
  107.         }
  108.         /*Este ciclo pintara todas las celdas de la fila 2
  109.         for (int i = 0; i < fila.getPhysicalNumberOfCells(); i++) {
  110.         HSSFCell cell = fila.getCell(i);
  111.         cell.setCellStyle(estilo);
  112.         }*/
  113.  
  114.    }
  115.  
  116.  

Se agradece cualquier ayuda, sugerencia, gracias de antemano.


Título: Re: Problema al crear excel
Publicado por: Pablo Videla en 4 Noviembre 2011, 21:52 pm
Disculpen el doble post, si editaba el mensaje el geshi se me iba a la shit, asi que publico aqui, debo señalar que al recuperar el excel generado me sale este mensaje al mostrar los errores.

Código
  1.  <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
  2. - <recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  3.  <logFileName>error027520_01.xml</logFileName>
  4.  <summary>Se han detectado errores en el archivo "C:\Documents and Settings\Administrador\Mis documentos\Downloads\6tff5e5tfg.xls"</summary>
  5. - <additionalInfo>
  6.  <info>Excel ha intentado recuperar las fórmulas y los valores de las celdas, pero algunos datos pueden haberse perdido.</info>
  7.  </additionalInfo>
  8.  </recoveryLog>

No uso formulas, solo lo que ven ustedes en el codigo, gracias de antemano y disculpen nuevamente.(Por romper la regla del doble post)


Título: Re: Problema al crear excel
Publicado por: Pablo Videla en 7 Noviembre 2011, 15:43 pm
Ok señores, recién pude solucionar el problema, la cosa es que lo hice todo desde cero nuevamente y nunca supe donde estaba el problema  :xD, disculpen los post seguidos pero si edito codigo el geshi muere, no se porque , los espacios se ven como asteriscos, pero acá colocare la solución, saludos.


Código
  1. public void exportarExcel() {
  2.        if (movimientos == null) {// Cargamos el ArrayList si esta nulo
  3.            cargaTablaDinamica();
  4.        }
  5.        HSSFWorkbook workbook = new HSSFWorkbook();//Creamos el libro excel
  6.  
  7.        /*Creamos la hoja de Excel llamada "Movimientos"*/
  8.        HSSFSheet sheet = workbook.createSheet("Movimientos");
  9.  
  10.        /* Creamos la primera fila para colocar los titulos correspondientes a
  11.          * cada columna*/
  12.  
  13.        HSSFRow header = sheet.createRow(0);
  14.        HSSFRow fila = null;
  15.  
  16.        for (int i = 0; i < movimientos.size(); i++) {
  17.            /* Creamos las filas segun la cantidad de datos que contiene
  18.              * el arraylist
  19.              */
  20.            fila = sheet.createRow(i + 1);
  21.  
  22.            /* Creamos las celdas, se sabe que son 5*/
  23.            for (int j = 0; j < 5; j++) {
  24.  
  25.                fila.createCell(j);
  26.  
  27.            }
  28.            /* Asignamos los titulos a la primera fila,
  29.              * en cada celda correspondiente */
  30.  
  31.            header.createCell(0).setCellValue(new HSSFRichTextString("Fecha"));
  32.            header.createCell(1).setCellValue(new HSSFRichTextString("Descripcion"));
  33.            header.createCell(2).setCellValue(new HSSFRichTextString("Serie"));
  34.            header.createCell(3).setCellValue(new HSSFRichTextString("Monto"));
  35.            header.createCell(4).setCellValue(new HSSFRichTextString("Saldo"));
  36.  
  37.            /* Seteamos los valores a cada celda correspondiente */
  38.            fila.getCell(0).setCellValue("" + movimientos.get(i).getFecha().toLocaleString());
  39.            fila.getCell(1).setCellValue(new HSSFRichTextString(movimientos.get(i).getDescripcion()));
  40.            fila.getCell(2).setCellValue(new HSSFRichTextString(movimientos.get(i).getSerie()));
  41.            fila.getCell(3).setCellValue(Integer.parseInt(String.valueOf(movimientos.get(i).getMonto()).replace(".0", "")));
  42.            fila.getCell(4).setCellValue(Integer.parseInt(String.valueOf(movimientos.get(i).getSaldo()).replace(".0", "")));
  43.  
  44.            /*Modificamos el tamaño de las celdas segun el contenido de las celdas*/
  45.  
  46.            sheet.autoSizeColumn((short) (i));
  47.  
  48.        }
  49.  
  50.        sheet.autoSizeColumn((short) (0));//Arreglamos el tamaño al header
  51.  
  52.        try {
  53.            FacesContext facesContext = FacesContext.getCurrentInstance();
  54.            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
  55.  
  56.            /* Le asignamos el tipo de fichero que abrirá*/
  57.            response.setContentType("application/vnd.ms-excel");
  58.            /* El nombre que recibira el archivo a descargar */
  59.            response.setHeader("Content-disposition", "attachment; filename=movimientos.xls");
  60.  
  61.            ServletOutputStream out = response.getOutputStream();
  62.            /*Escribimos el fichero al out */
  63.            workbook.write(out);
  64.            out.close(); // Cerramos el streaming
  65.  
  66.        } catch (Exception e) {
  67.            e.printStackTrace();
  68.  
  69.  
  70.        }
  71.  
  72.  
  73.  
  74.    }
  75.  
  76.