Exportar datos de jTable a Excel

Les dejo para que puedan exportar los datos de un jTable a Excel:

1) Descarga de la librería necesaria: jExcelApi

2) Creamos "Exporter.java", les dejé como comentario el for sin titulos de columnas por si lo necesitan así:

package bco2.ClasesGenericas;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.swing.JTable;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 *
 * @author JP Blanco
 */
public class Exporter {
    private File file;
    private List<JTable> tabla;
    private List<String> nom_files;

    public Exporter(File file, List<JTable> tabla, List<String> nom_files) throws Exception {
        this.file = file;
        this.tabla = tabla;
        this.nom_files = nom_files;
        if (nom_files.size()!=tabla.size()) {
            throw new Exception ("Error");
        }
    }
   
    public boolean export() {
       
        try {
            DataOutputStream out=new DataOutputStream (new FileOutputStream(file));
            WritableWorkbook w = Workbook.createWorkbook(out);
            for (int index=0; index<tabla.size(); index++){
                JTable table=tabla.get(index);
                WritableSheet s=w.createSheet(nom_files.get(index),0);
               //Para que salga el titulo de las columnas
for (int i = 0; i < table.getColumnCount(); i++) {
      for (int j = 0; j < table.getRowCount(); j++) {
            Object titulo = table.getColumnName(i);
            s.addCell(new Label(i+1, j+1, String.valueOf(titulo)));
       }
}
for (int i = 0; i < table.getColumnCount(); i++) {
      for (int j = 0; j < table.getRowCount(); j++) {
            Object object = table.getValueAt(j, i);
            s.addCell(new Label(i+1, j+2, String.valueOf(object)));
      }
    }
             /*
            *    for sin titulo de columnas:
            *
            *  for (int i=0; i<table.getColumnCount(); i++){
            *     for (int j=0; j<table.getRowCount();j++){
            *         Object object=table.getValueAt(j,i);
            *         s.addCell (new Label(i,j,String.valueOf(object)));
            *       
            *     }  
            * }
            **/

            }
            w.write();
            w.close();
            return true;
        }

        catch (IOException | WriteException e) {
            return false;
        }
    }
   
   
}


3) Agregamos un jFrame o en el proyecto que uds ya estén usando y creamos un botón "Exportar":

  private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        if (this.tabla.getRowCount()==0) {
            JOptionPane.showMessageDialog (null, "No hay datos en la tabla para exportar.","BCO",
                JOptionPane.INFORMATION_MESSAGE);
            this.cmbConsorcio.grabFocus();
            return;
        }
        JFileChooser chooser=new JFileChooser();
        FileNameExtensionFilter filter=new FileNameExtensionFilter("Archivos de excel","xls");
        chooser.setFileFilter(filter);
        chooser.setDialogTitle("Guardar archivo");
        chooser.setMultiSelectionEnabled(false);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION){
            List<JTable> tb=new ArrayList<>();
            List<String>nom=new ArrayList<>();
            tb.add(tabla);
            nom.add("Detalle de Gastos");
            String file=chooser.getSelectedFile().toString().concat(".xls");
            try {
                bco2.ClasesGenericas.Exporter e=new Exporter(new File(file),tb, nom);
                if (e.export()) {
                    JOptionPane.showMessageDialog(null, "Los datos fueron exportados a excel.","BCO",
                        JOptionPane.INFORMATION_MESSAGE);

                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null,"Hubo un error"+ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            }
        }

    }


No se olviden de importar "Exporter".

7 comentarios:

  1. como podria enviar tambien una imagen, y que los titulos de la tabla se pongan negritos o ponerles color

    ResponderEliminar
  2. Muchas gracias. Y como podría agregar la funcionalidad de que los campos fueran exportados de distintos tamaños y no como un estándar.
    Saludos
    enriqueruiz1841@gmail.com

    ResponderEliminar
  3. use este codigo pero me die que no acepta un string..
    s.addCell(new Label(i+1, j+1, String.valueOf(titulo))); //esa parte del codigo me marca error..sera que puedan ayudarme porfa

    ResponderEliminar
  4. Siento un profundo amor por ti en estos momentos!!

    ResponderEliminar
  5. como enviar también una imagen, y que los títulos de la tabla se pongan negritos o ponerles color...

    ResponderEliminar