Bonjour
ci joint un code pour importer/exporter un fichier excel(je l'ai recuperé sur un site) :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
package gestionexcel;
 
import gestionexcel.Vista.VistaExcel;
 
public class GestionExcel {
 
       public static void main(String[] args) {
           VistaExcel ve = new VistaExcel();
           ve.setVisible(true);
       }
}
ensuite :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package gestionexcel.Vista;
 
public class VistaExcel extends javax.swing.JFrame {
 
    public VistaExcel() {
        initComponents();
    }
 
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
 
        BtnImporter = new javax.swing.JButton();
        BtnExporter = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtDatos = new javax.swing.JTable();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        BtnImporter.setText("IMPORTER");
        BtnImporter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnImporterActionPerformed(evt);
            }
        });
 
        BtnExporter.setText("EXPORTER");
 
        jtDatos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
 
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };
 
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtDatos.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jtDatos);
        if (jtDatos.getColumnModel().getColumnCount() > 0) {
            jtDatos.getColumnModel().getColumn(0).setResizable(false);
            jtDatos.getColumnModel().getColumn(1).setResizable(false);
            jtDatos.getColumnModel().getColumn(2).setResizable(false);
            jtDatos.getColumnModel().getColumn(3).setResizable(false);
        }
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(BtnImporter)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnExporter)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(38, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BtnImporter)
                    .addComponent(BtnExporter))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(210, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>//GEN-END:initComponents
 
    private void BtnImporterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnImporterActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_BtnImporterActionPerformed
 
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton BtnExporter;
    public javax.swing.JButton BtnImporter;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable jtDatos;
    // End of variables declaration//GEN-END:variables
}
ensuite :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
 
package gestionexcel.Modelo;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
 
public class ModeloExcel {
    Workbook wb;
 
    public String Importar(File archivo, JTable tablaD){
        String respuesta="Ne peut pas s'importer";
        DefaultTableModel modeloT=new DefaultTableModel();
        tablaD.setModel(modeloT);
        try {
            wb =WorkbookFactory.create(new FileInputStream(archivo));
            Sheet hoja = wb.getSheetAt(0);
            Iterator filaIterator = hoja.rowIterator();
            int indiceFila=-1;
            while (filaIterator.hasNext()) {
                indiceFila++;
                Row fila=(Row) filaIterator.next();
                Iterator columnaIterator=fila.cellIterator();
                Object[] listaColumna=new Object[5];
                int indiceColumna=-1;
                while (columnaIterator.hasNext()){
                    indiceColumna++;
                    Cell celda= (Cell) columnaIterator.next();
                    if(indiceFila==0){
                        modeloT.addColumn(celda.getStringCellValue());
                    }else{
                        if (celda!=null){
                            switch (celda.getCellType()) {
                                case NUMERIC:
                                    listaColumna[indiceColumna]=(int)Math.round(celda.getNumericCellValue());
                                    break;
                                case STRING:
                                    listaColumna[indiceColumna]=celda.getStringCellValue();
                                    break;
                                case BOOLEAN:
                                    listaColumna[indiceColumna]=celda.getBooleanCellValue();
                                    break;
                                default:
                                    listaColumna[indiceColumna]=celda.getDateCellValue();
                                    break;   
                            }
                        }
                    }
                }
                if(indiceFila!=0)modeloT.addRow(listaColumna);
            }
            respuesta="Importation réussi";
        } catch (Exception e) {
        }
        return respuesta;
    }
 
    public String Exportar(File archivo, JTable tablaD){
        String respuesta="L'exportation a échoué";
        int numFila=tablaD.getRowCount(), numColumna=tablaD.getColumnCount();
        if(archivo.getName().endsWith("xls")){
            wb=new HSSFWorkbook();
        }else{
            wb=new XSSFWorkbook();
        }
        Sheet hoja = wb.createSheet("Test");
        try {
            for (int i = 0; i < numFila; i++){
              Row fila = hoja.createRow(+1);
              for (int j = 0; j < numColumna; j++){
                  Cell celda = fila.createCell(j);
                  if(i==-1){
                      celda.setCellValue(String.valueOf(tablaD.getColumnName(j)));
                  }else{
                      celda.setCellValue(String.valueOf(tablaD.getValueAt(i,j)));
                  }
                  wb.write(new FileOutputStream(archivo));
              }
            }
            respuesta="Réussie";
        } catch (Exception e) {
        }
        return respuesta;
    }
}
et finalement :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package gestionexcel.Controlador;
 
import gestionexcel.Modelo.ModeloExcel;
import gestionexcel.Vista.VistaExcel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
 
 
public class ControladorExcel implements ActionListener{
    ModeloExcel modeloE = new ModeloExcel();
    VistaExcel vistaE = new VistaExcel();
    JFileChooser selecArchivo = new JFileChooser();
    File archivo;
    int contAccion=0;
 
    public ControladorExcel(VistaExcel vistaE,ModeloExcel modeloE){
        this.vistaE=vistaE;
        this.modeloE=modeloE;
        this.vistaE.BtnImporter.addActionListener(this);
        this.vistaE.BtnExporter.addActionListener(this);
    }
 
    public void AgregarFiltro(){
        selecArchivo.setFileFilter(new FileNameExtensionFilter("Excel (*.xls)", "xls"));
        selecArchivo.setFileFilter(new FileNameExtensionFilter("Excel (*.xlsx)", "xlsx"));
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        contAccion++;
        if(contAccion==1)AgregarFiltro();
 
        if(e.getSource() == vistaE.BtnImporter){
            if(selecArchivo.showDialog(null, "Selectionner l'archive")== JFileChooser.APPROVE_OPTION){
               archivo = selecArchivo.getSelectedFile();
               if(archivo.getName().endsWith("xls") || archivo.getName().endsWith("xlsx")){
                  JOptionPane.showMessageDialog(null,modeloE.Importar(archivo, vistaE.jtDatos));    
               }else{
                   JOptionPane.showMessageDialog(null," Choisir un format valide");
               }
            }
        }
        if(e.getSource() == vistaE.BtnExporter){
            if(selecArchivo.showDialog(null, "Exporter")== JFileChooser.APPROVE_OPTION){
               archivo=   selecArchivo.getSelectedFile();
               if(archivo.getName().endsWith("xls") || archivo.getName().endsWith("xlsx")){
                  JOptionPane.showMessageDialog(null,modeloE.Exportar(archivo, vistaE.jtDatos));    
               }else{
                   JOptionPane.showMessageDialog(null," Choisir un format valide");
               }
            }
        }    
    }  
}
les librairies sont bien installées.
Quand je lance le programme, ma fenêtre s'affiche bien, mais lorsque je clique sur mes boutons "Exporter" ou "Importer" il ne se passe rien ??
Clean & Build ne me révèle aucune erreur.