IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Eclipse Java - Extraire Jtable vers Microsoft Excel


Sujet :

avec Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti Avatar de wilder1626
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2018
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Canada

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2018
    Messages : 12
    Par défaut Eclipse Java - Extraire Jtable vers Microsoft Excel
    Bonjour.

    Je suis nouveau en Java - Éclipse et je tente d'extraire l'info de mon JTable en excel, mais aucun résultat. Il m'affiche bien le message à la fin mais aucun fichier excel avec le data.
    Voyez-vous ou se trouve le problème? Merci pour votre aide.

    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
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import java.io.File;
     
    public class test_no_1 {
     
    	/**
             * Launch the application.
             */
    	public static void main(String[] args) {
            String[][] data = {{"Meubles", "Rs.1275.00"},
                    {"Outils", "Rs.125.00"}, {"Électroniques", "Rs.2533.00"},
                    {"Bois", "Rs.497.00"}
                };
                String[] headers = {"Départment", "Revenue"};
     
                JFrame frame = new JFrame("JTable to Excel");
                DefaultTableModel model = new DefaultTableModel(data, headers);
                final JTable table = new JTable(model);
                JScrollPane scroll = new JScrollPane(table);
     
                JButton export = new JButton("Export");
     
                export.addActionListener(new ActionListener() {
     
                    @Override
                    public void actionPerformed(ActionEvent evt) {
     
                        try {
                            ExcelExporter exp = new ExcelExporter();
                            exp.fillData(table, new File("C:\\result.xls"));
                            JOptionPane.showMessageDialog(null, "Data sauvegardé vers " +
                                    "'C:\\result.xls' successfully", "Message",
                                    JOptionPane.INFORMATION_MESSAGE);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
     
                frame.getContentPane().add("Center", scroll);
                frame.getContentPane().add("South", export);
                frame.pack();
                frame.setVisible(true);
             //   frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
     
    	;
    	}
     
    }

  2. #2
    Membre éprouvé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2018
    Messages
    80
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Juin 2018
    Messages : 80
    Par défaut
    Bonsoir,

    Il nous faudrait un peu plus d'information. Que fait la méthode "fillData" de l'objet ExcelExporter ?

    Regardez du côté des méthodes de l'objet "ExcelExporter", voir si vous ne devez pas créer une feuille dans le classeur, enregistrer le classeur...

    Bon courage

  3. #3
    Membre averti Avatar de wilder1626
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2018
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Canada

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2018
    Messages : 12
    Par défaut
    Je viens de changer ma façon de faire et je crois que ça marche.

    je vais faire quelque testes.

    Je ne sais pas si le code peut-être optimisé parcontre?

    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
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import javax.swing.JButton;
    import javax.swing.GroupLayout;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionListener;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.awt.event.ActionEvent;
     
    public class test4 {
      public static void main(String[] argv) throws Exception {
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);
     
        model.addColumn("Départment");
        model.addColumn("Revenue");
     
        // Create the first row
        model.insertRow(0, new Object[] { "Meubles","Rs.1275.00" });
     
        // Insert a row at position p
        int p = 1;
        model.insertRow(p, new Object[] { "Outils","Rs.125.00"});
        model.insertRow(p, new Object[] { "Électroniques","Rs.497.00"});
     
        JFrame f = new JFrame();
        f.setSize(585, 460);
        JScrollPane scrollPane = new JScrollPane(table);
     
        JButton button = new JButton("Export to Excel");
        scrollPane.setColumnHeaderView(button);
        GroupLayout groupLayout = new GroupLayout(f.getContentPane());
        groupLayout.setHorizontalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 569, GroupLayout.PREFERRED_SIZE)
        );
        groupLayout.setVerticalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 421, GroupLayout.PREFERRED_SIZE)
        );
     
        JButton btnNewButton = new JButton("Export to Excel");
        btnNewButton.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
     
        		//extract to excel
        		   try{
        		        TableModel model = table.getModel();
        		        FileWriter excel = new FileWriter("C:\\result.xls");
        		        for(int i = 0; i < model.getColumnCount(); i++){
        		            excel.write(model.getColumnName(i) + "\t");
        		        }
     
        		        excel.write("\n");
     
        		        for(int i=0; i< model.getRowCount(); i++) {
        		            for(int j=0; j < model.getColumnCount(); j++) {
        		                excel.write(model.getValueAt(i,j).toString()+"\t");
        		            }
        		            excel.write("\n");
        		        }
     
        		        excel.close();
        		        JOptionPane.showMessageDialog(null, "Data sauvegardé vers " +
                                "'C:\\result.xls' successfully", "Message",
                                JOptionPane.INFORMATION_MESSAGE);
        		    }catch(IOException e1){ System.out.println(e); }
        		}
     
        });
        scrollPane.setRowHeaderView(btnNewButton);
        f.getContentPane().setLayout(groupLayout);
        f.setVisible(true);
      }
    }

  4. #4
    Membre éprouvé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2018
    Messages
    80
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Juin 2018
    Messages : 80
    Par défaut
    Bonsoir,

    Pour un aussi simple besoin, ceci peut suffire.

    Si vous souhaitez, aller plus loin, je vous conseille d'utiliser la librairie POI Apache : https://poi.apache.org/

    Bon courage

  5. #5
    Membre averti Avatar de wilder1626
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2018
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Canada

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2018
    Messages : 12
    Par défaut
    je vois qu'il y a plusieurs et bonnes aventages d'utiliser POI Apache.

    Je sais pas trop comment faire pour le moment, mais je vais l'utilisé. Je vais revenir si j'ai des problèmes. Je viens de télécharger poi-4.0.1.

  6. #6
    Membre averti Avatar de wilder1626
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2018
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Canada

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2018
    Messages : 12
    Par défaut
    Voici la version avec POI Apache.

    Parcontre, je me trouve avec une erreur que je ne comprend pas trop.

    Est-ce que tu pourais m'aider s.v.p?

    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
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at test6$1.actionPerformed(test6.java:53)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    	at java.awt.Component.processMouseEvent(Component.java:6533)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    	at java.awt.Component.processEvent(Component.java:6298)
    	at java.awt.Container.processEvent(Container.java:2236)
    	at java.awt.Component.dispatchEventImpl(Component.java:4889)
    	at java.awt.Container.dispatchEventImpl(Container.java:2294)
    	at java.awt.Component.dispatchEvent(Component.java:4711)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    	at java.awt.Container.dispatchEventImpl(Container.java:2280)
    	at java.awt.Window.dispatchEventImpl(Window.java:2746)
    	at java.awt.Component.dispatchEvent(Component.java:4711)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    	at java.awt.EventQueue.access$500(EventQueue.java:97)
    	at java.awt.EventQueue$3.run(EventQueue.java:709)
    	at java.awt.EventQueue$3.run(EventQueue.java:703)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    	at java.awt.EventQueue$4.run(EventQueue.java:731)
    	at java.awt.EventQueue$4.run(EventQueue.java:729)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

    Code complet:

    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
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     
    import javax.swing.JButton;
    import javax.swing.GroupLayout;
    import javax.swing.GroupLayout.Alignment;
    import java.awt.event.ActionListener;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.awt.event.ActionEvent;
    import javax.swing.LayoutStyle.ComponentPlacement;
     
    public class test6 {
      public static void main(String[] argv) throws Exception {
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);
     
        model.addColumn("Départment");
        model.addColumn("Revenue");
     
        // Create the first row
        model.insertRow(0, new Object[] { "Meubles","Rs.1275.00" });
     
        // Insert a row at position p
        int p = 1;
        model.insertRow(p, new Object[] { "Outils","Rs.125.00"});
        model.insertRow(p, new Object[] { "Électroniques","Rs.497.00"});
     
        JFrame f = new JFrame();
        f.setSize(602, 433);
        JScrollPane scrollPane = new JScrollPane(table);
     
        JButton btnPoiExcel = new JButton("POI Excel");
        btnPoiExcel.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
     
        		String excelFileName = "C:\\Excel_test.xlsx";//name of excel file
        		String sheetName = "Sheet1";//name of sheet
     
        		XSSFWorkbook wb = new XSSFWorkbook();
        		XSSFSheet sheet = wb.createSheet(sheetName) ;
     
        		//iterating r number of rows
        		for (int r=0;r < 5; r++ )
        		{
        			XSSFRow row = sheet.createRow(r);
     
        			//iterating c number of columns
        			for (int c=0;c < 5; c++ )
        			{
        				XSSFCell cell = row.createCell(c);
     
        				cell.setCellValue("Cell "+r+" "+c);
        			}
        		}
     
        		FileOutputStream fileOut = null;
    			try {
    				fileOut = new FileOutputStream(excelFileName);
    			} catch (FileNotFoundException e2) {
    				// TODO Auto-generated catch block
    				e2.printStackTrace();
    			}
     
        		//write this workbook to an Outputstream.
        		wb.write(fileOut);
        		try {
    				fileOut.flush();
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
        		try {
    				fileOut.close();
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}  		
        	}
        });
     
     
     
     
        GroupLayout groupLayout = new GroupLayout(f.getContentPane());
        groupLayout.setHorizontalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        				.addComponent(btnPoiExcel)
        				.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 569, GroupLayout.PREFERRED_SIZE))
        			.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        groupLayout.setVerticalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addContainerGap()
        			.addComponent(btnPoiExcel)
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 328, GroupLayout.PREFERRED_SIZE)
        			.addContainerGap(21, Short.MAX_VALUE))
        );
     
        JButton btnNewButton_1 = new JButton("New button");
        scrollPane.setColumnHeaderView(btnNewButton_1);
        f.getContentPane().setLayout(groupLayout);
        f.setVisible(true);
      }
    }

Discussions similaires

  1. Eclipse - Extraire Jtable vers Microsoft Excel
    Par wilder1626 dans le forum Eclipse Java
    Réponses: 2
    Dernier message: 02/01/2019, 16h26
  2. Envoie de donnée vers Microsoft Excel
    Par tomtom92 dans le forum C#
    Réponses: 2
    Dernier message: 11/03/2015, 14h05
  3. Extraire tableaux vers fichier Excel
    Par meumeu73.1 dans le forum QlikView
    Réponses: 5
    Dernier message: 22/05/2013, 12h47
  4. [VB Project] Excel Vba vers Microsoft Project
    Par Mut dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 12/10/2006, 12h06
  5. Accéder à Microsoft Excel, Word via Java ? Possible?
    Par ADONET dans le forum Documents
    Réponses: 8
    Dernier message: 27/01/2006, 20h16

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo