jueves, 12 de abril de 2012

Tutorial : Java Swing Exportar a Excel con Apache POI y JFileChooser - Parte 7.2.1



Continuando con el tutorial sobre el formulario Producto, implementaremos la funcionalidad para exportar nuestra tabla a un archivo Microsoft Excel con extensión XLS.



Creamos un evento en nuestro boton btnExportar ey incluimos el siguiente codigo

private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {
        //creamos un filtro de archivos para definir que archivos ver en el JFileChooser
        javax.swing.filechooser.FileNameExtensionFilter filterXls = new javax.swing.filechooser.FileNameExtensionFilter("Documentos MS Excel 95/2003", "xls");

        //instanciamos una ventana de seleccion de archivo
        final JFileChooser fc = new JFileChooser();

        //agregamos el filtro al filechooser
        fc.setFileFilter(filterXls);

        //capturamos la respuesta del usuario
        int returnVal = fc.showSaveDialog(null);

        //definimos el comportamiento de la ventana
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        if (returnVal == JFileChooser.APPROVE_OPTION) {

            FileOutputStream fileOut = null;
            File fileXLS = null;
            try {
                //Creamos un objeto archivo con la ruta seleccionada
                fileXLS = fc.getSelectedFile();

 //Validamos si en la ruta el archivo se ha especificado la extensión
                String name = fileXLS.getName();
                if (name.indexOf('.') == -1) {
       //De no ser asi le agregamos
                    name += ".xls";
                    fileXLS = new File(fileXLS.getParentFile(), name);
                }
                fileOut = new FileOutputStream(fileXLS);
                //Creamos la cabecera
                final String[] headers = {"CODIGO", "DESCRIPCION", "PRECIO"};

 //Creamos el libro Excel
                Workbook wb = new HSSFWorkbook();                                
 //Creamos una nueva Hoja
                Sheet sheet = wb.createSheet("PRODUCTOS");

 //Definimos el estilo de la cabecera
                CellStyle headerStyle = wb.createCellStyle();
  //Color de fondo
                headerStyle.setFillBackgroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
  //Estilo de la fuente
                Font hfont = wb.createFont();
                hfont.setBoldweight(Font.BOLDWEIGHT_BOLD);
                headerStyle.setFont(hfont);
  //Alineacion Horizontal
                headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
                // Creamos una fila, las filas empiezan en 0
                Row titleRow = sheet.createRow((short) 0);
  //Creamos una celda para nuestra fila
                Cell hCell = titleRow.createCell((short) 0);                
 //Asignamos un valor a la celda
                hCell.setCellValue("Lista de Productos");
 //Vamos a unir nuestra celdas de la primera fila
                sheet.addMergedRegion(new CellRangeAddress(
                        0, //first row (0-based)
                        0, //last row  (0-based)
                        0, //first column (0-based)
                        headers.length-1 //last column  (0-based)
                        ));
                //Asignamos el estilo que deseamos
                hCell.setCellStyle(headerStyle);
 //Creamos una nueva fila para las cabeceras
                Row row = sheet.createRow((short) 1);
 /**
  Creamos nuestras celdas de acuerdo a nuestro array headers
  Por cada cabecera creamos una celda y le asignamos el estilo.
 */
                for (int i = 0; i < headers.length; i++) {  
                    Cell cell = row.createCell(i);
                    cell.setCellValue(headers[i]);
                    cell.setCellStyle(headerStyle);
  //Asigna automaticamente el tamaño
                    sheet.autoSizeColumn(i);
                }
  /**
  Variable para saber en que fila estamos, se inicializa en 2 porque ya hemos creado 2   filas antes.
  */
                int rowIndex=2;
 //Recorremos los objetos Producto que tiene nuestra tabla
                for (Producto p : productoTableModel.getData()) {       
  //Por cada objeto creamos una fila              
                     Row newRow = sheet.createRow((short) rowIndex);
  //Creamos una celda por cada campo de nuestro objeto
                     newRow.createCell(0).setCellValue(p.getCodigo());
                     newRow.createCell(1).setCellValue(p.getDescripcion());
                     newRow.createCell(2).setCellValue(p.getPrecio().toString());
  /*
   Aumentamos nuestra variable de manera que en la siguiente iteracion salta a otra fila
  */
                     rowIndex++;
                }
                                

                for (int i = 0; i < headers.length; i++) {
                    sheet.autoSizeColumn(i);
                }
 // Escribimos el libro
                wb.write(fileOut);
            } catch (IOException ex) {
                Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
  //Cerramos nuestro archivo
                    fileOut.close();
                    //abrimos el archivo generado con el programa correspondiente
                    if (System.getProperty("os.name").equals("Linux")) {
                        Runtime.getRuntime().exec("libreoffice " + fileXLS.getAbsolutePath());
                    } else {
                        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + fileXLS.getAbsolutePath());
                    }

                } catch (IOException ex) {
                    Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

El codigo es casi auto explicativo, si tienen dudas hacerlas en los comentarios que con gusto nos ayudamos. Viene de Tutorial : Implementar funcionalidad de Formulario Productos - Parte 7.2

5 comentarios:

  1. Sabes como crear una tabla excel desde java, asi como la tabla de esta imagen: http://s2.subirimagenes.com/imagen/previo/thump_7708537imagentabla.png
    POrfavor lo necesito urgente para un proyecto de la Universidad.

    ResponderEliminar
  2. La imagen no se aprecia muy bien pero creo podria tirarte algo de codigo de ayuda, por lo que veo quieres algunas celdas unidas.

    sheet.addMergedRegion(new CellRangeAddress(
    0, //primera fila (0-based)
    3, //ultima fila (0-based)
    0, //primera columna (0-based)
    0 //ultima columna (0-based)
    ));
    Esto indica unir las celdas A1 hasta A4.

    Espero te sirva

    ResponderEliminar
  3. Holas,,,estoy siguiendo el tuto...sta interesante,,,cuando continuas con el resto?

    ResponderEliminar
  4. Saludos me a gustado el codigo pero necesito que me digas como as construido tu metodo .getData() de tu table model

    ResponderEliminar
  5. ESTIMADO SI CADA FILA CORRESPONDIERA A UN FORMATO Y QUISIERA EXPORTARLO EN UN ARCHIVO EXCEL EN VARIAS PESTAÑAS Y EN CADA ETIQUETA ME PUSIERA EL ID DE CADA FILA EJEM

    ResponderEliminar

 
Powered by Blogger