PhoenixCamus
Usuario (Perú)
/*1RO CREAMOS LA CLASE*/ package excelimporter; import java.io.*; import javax.swing.*; import jxl.write.*; import jxl.*; public class ExcelTableExporter { private File file; private JTable table; private String nombreTab; public ExcelTableExporter(JTable table,File file,String nombreTab){ this.file=file; this.table=table; this.nombreTab=nombreTab; } public boolean export(){ try { //Nuestro flujo de salida para apuntar a donde vamos a escribir DataOutputStream out=new DataOutputStream(new FileOutputStream(file)); //Representa nuestro archivo en excel y necesita un OutputStream para saber donde va locoar los datos WritableWorkbook w = Workbook.createWorkbook(out); WritableSheet s = w.createSheet(nombreTab, 0); for(int i=0;i< table.getColumnCount();i++){ for(int j=0;j<table.getRowCount();j++){ Object objeto=table.getValueAt(j,i); s.addCell(new Label(i, j, String.valueOf(objeto))); } } //Como excel tiene muchas hojas esta crea o toma la hoja //Coloca el nombre del "tab" y el indice del tab w.write(); //Cerramos el WritableWorkbook y DataOutputStream w.close(); out.close(); //si todo sale bien salimos de aqui con un true return true; }catch(IOException ex){ex.printStackTrace();} catch(WriteException ex){ex.printStackTrace();} //Si llegamos hasta aqui algo salio mal return false; } } /*2DO EL FRAME DONDE LO VAMOS A LLAMAR*/ package excelimporter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.Calendar; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import jxl.Cell; import jxl.CellType; import jxl.DateCell; import jxl.LabelCell; import jxl.NumberCell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class DialogoImport extends javax.swing.JDialog { private DefaultTableModel defaultTableModel; private Workbook wbook; public DialogoImport(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); /*Permite cerrar el fichero despues que se cierra el dialogo*/ this.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { super.windowClosed(e); if(wbook!=null ) wbook.close(); } }); } private void createTableModel(File file) { try { //getting the workbook wbook = Workbook.getWorkbook(file); //una hoja en especifico final Sheet hoja = wbook.getSheet(0); Cell a1 = hoja.getCell(0, 0); final int columnas = hoja.getColumns(); final int filas = hoja.getRows(); defaultTableModel = new DefaultTableModel() { @Override public String getColumnName(int column) { Cell cell = hoja.getCell(column, 0); LabelCell lc = (LabelCell) cell; return lc.getString(); } @Override public int getColumnCount(){ return columnas; } @Override public boolean isCellEditable(int row, int col) { return false; } @Override public int getRowCount() { return filas-getColumnCount()-1; } @Override public Object getValueAt(int row, int col) { row++; Cell cell = hoja.getCell(col, row); if (cell.getType() == CellType.LABEL) { LabelCell lc = (LabelCell) cell; return lc.getString(); } else if (cell.getType() == CellType.NUMBER) { NumberCell nc = (NumberCell) cell; return nc.getValue(); } else if (cell.getType() == CellType.DATE) { DateCell dc = (DateCell) cell; String fecha = ""; Calendar cal = Calendar.getInstance(); cal.setTime(dc.getDate()); int dia = cal.get(Calendar.DAY_OF_MONTH)+1; int mes = cal.get(Calendar.MONTH) + 1; String sDia = ""; String sMes = ""; if(dia < 10) sDia = "0"; sDia += dia; if(mes < 10) sMes = "0"; sMes += mes; fecha = sDia + "/" + sMes + "/" + cal.get(Calendar.YEAR); return fecha; } return null; } }; this.jTable1.setModel(defaultTableModel); } catch (IOException ex) { ex.printStackTrace(); } catch (BiffException ex) { ex.printStackTrace(); } } @SuppressWarnings("unchecked" // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jScrollPane1.setViewportView(jTable1); jButton1.setText("jButton1"; jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jMenu1.setText("Archivo"; jMenuItem1.setText("Importar"; jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1) .addContainerGap(188, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { int answer = this.jFileChooser1.showDialog(null, "Importar"; if (answer == JFileChooser.APPROVE_OPTION) { File archivo = jFileChooser1.getSelectedFile(); if (archivo != null) { createTableModel(archivo); } } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { ExcelTableExporter excelExporter = new ExcelTableExporter (jTable1, new File("exportar.xls","Prueba"; if (excelExporter.export()) { JOptionPane.showMessageDialog(null, "Exportado con exito!"; } } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration public static void main(String[] args) { new DialogoImport(null, false).setVisible(true); } }