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

Documents Java Discussion :

JTabbedPane JTable JPanel Excel (xls, xlsx) Apache POI


Sujet :

Documents Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 213
    Points : 96
    Points
    96
    Par défaut JTabbedPane JTable JPanel Excel (xls, xlsx) Apache POI
    Bonjour à tous,

    J'ai le problème suivant qui est peut-être assez claire mais je n'y arrive pas encore :
    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
     
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Zip File is closed
    	at org.apache.poi.openxml4j.util.ZipFileZipEntrySource.getEntries(ZipFileZipEntrySource.java:45)
    	at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:180)
    	at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:696)
    	at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:230)
    	at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:188)
    	at org.apache.poi.POIXMLDocument.openPackage(POIXMLDocument.java:85)
    	at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:319)
    	at EVENT.MyUtilityMethods.createTabPanel(MyUtilityMethods.java:71)
    	at EVENT.MyActionEvent.btnLoad_click(MyActionEvent.java:67)
    	at EVENT.MyActionEvent.actionPerformed(MyActionEvent.java:34)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Et Maintenant la classe MyUtilityMethods :
    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
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
     
    package EVENT;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.List;
     
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
     
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    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;
     
    /**
     * Some utility methods for the application
     * 
     * @author t0163126
     */
    public class MyUtilityMethods {
     
    	/**
             * Create  tabs based on file and panel 
             * 
             * @param tabPanel
             * @param file
             * @return
             */
    	public JTabbedPane createJTabbed(List<JPanel> lstPanel, File file) {
     
    		JTabbedPane tabbedPane = new JTabbedPane();
     
    		for (JPanel panel : lstPanel) {
    			int index = tabbedPane.getTabCount();
    			JComponent tabPanel = createTabPanel(file);
    			tabbedPane.addTab
    			(
    				panel.getName(), //tab name 
    				null, //tab icon
    				tabPanel, //Tabs panel for the JTable 
    				panel.getToolTipText() //tab tool tip text
    			);
    		}
    		return tabbedPane;
    	}
     
    	/**
             * Create a tab panel by excel feel
             * 
             * @param fileName
             * @param excelFile
             * @return
             */
    	public JComponent createTabPanel(File excelFile) {
    		JTable spreadsheet = new JTable();
    		JPanel panel = null;
    		XSSFWorkbook wb;
    		XSSFSheet sheet;
     
    		try {
    			wb = new XSSFWorkbook(excelFile.getName());
    			//Get the sheet number
    			int nbFeuilles = wb.getNumberOfSheets();
    			for (int i = 0; i < nbFeuilles; i++) {
    				sheet = wb.getSheetAt(i);
    				//Create one JTable by excel feel
    				spreadsheet = createJTableWithExcel(excelFile, i);
     
    				spreadsheet.setFont(new Font(Font.SERIF, Font.PLAIN, 10));
    				JScrollPane elevator = new JScrollPane();
    				elevator.setViewportView(spreadsheet);
    				//Create a panel by excel feel number
    				panel = new JPanel();
    				panel.setBorder(BorderFactory.createTitledBorder(sheet.getSheetName()));
    				panel.setBackground(Color.LIGHT_GRAY);
    				panel.add(elevator);
    			}
    			wb.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return panel;
    	}
     
    	/**
             * Create a JTable depending on the file and the entry sheet number
             * 
             * @param file
             * @param numSheet
             * @return
             */
    	public static JTable createJTableWithExcel(File file, int numSheet) {
    		// Create new table
    		JTable table = new JTable();
    		// Reading the excel file
    		XSSFWorkbook wb;
    		try {
    			wb = new XSSFWorkbook(file);
    			// Get the contents of the excel file according to the sheet number
    			XSSFSheet sheet = wb.getSheetAt(numSheet);
     
    			// Count the line number
    			int nbRows = sheet.getLastRowNum();
    			// Count the column number
    			int nbColumns = numberMaxColumn(sheet);
     
    			System.out.println("In the sheet " + sheet.getSheetName()
    					+ " there are " + nbRows + " lines and " + nbColumns
    					+ " columns");
     
    			// Create new object array
    			Object[][] obj = new Object[nbRows][nbColumns];
     
    			// Array header
    			String[] title = new String[nbColumns];
    			for (int i = 0; i < nbColumns; i++) {
    				title[i] = "#" + i;
    			}
     
    			// Browsing the sheet and retrieves the lines one by one
    			for (int rowContent = 0; rowContent < nbRows; rowContent++) {
    				XSSFRow row = sheet.getRow(rowContent);
     
    				// Browsing the line and retrieves the columns
    				if (row != null) {
    					for (int columnContent = 0; columnContent < nbColumns; columnContent++) {
    						// Retrieves the cell and this value
    						XSSFCell cell = row.getCell((short) columnContent);
    						Object value = contentCell(cell);
    						// System.out.println(value.toString());
    						obj[rowContent][columnContent] = value;
    					}
    				}
    			}
     
    			wb.close();
    			table.setModel(new DefaultTableModel(obj, title));
    		} catch (InvalidFormatException e) {
    			e.printStackTrace();
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return table;
    	}
     
    	/**
             * The cell can contain different type of value that should be specifically
             * recovered
             * 
             * @param cell
             * @return
             */
    	private static Object contentCell(XSSFCell cell) {
    		Object value = null;
     
    		if (cell == null) {
    			value = "";
    		} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
    			value = cell.getBooleanCellValue();
    		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_ERROR) {
    			value = cell.getErrorCellValue();
    		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
    			value = cell.getCellFormula();
    		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
    			value = cell.getNumericCellValue();
    		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
    			value = cell.getStringCellValue();
    		}
    		return value;
    	}
     
    	/**
             * Retrieves the maximum number of column. If a line has 2 empty boxes at
             * the end , they are not taken into account. So to retrieve the number of
             * columns to initialize our table we must browse all lines
             * 
             * @param sheet
             * @return
             */
    	private static int numberMaxColumn(XSSFSheet sheet) {
    		int r = sheet.getLastRowNum();
    		int max = 0;
    		int s = 0;
    		while (s < r) {
    			if (sheet.getRow(s) != null) {
    				int c = sheet.getRow(s).getLastCellNum();
    				if (c > max) {
    					max = c;
    				}
    			}
    			s++;
    		}
    		return max + 1;
    	}
    }
    Puis la méthode load_click de la classe MyActionEvent qui se déclanche lors d'un clique sur le bouton Load :
    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
     
    private void btnLoad_click() 
    	{
    		JFileChooser fc = new MyFileChooser();
     
    		//Open the dialog box
    		int returnVal = fc.showOpenDialog(null);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			//if you validate
    			MyUtilityMethods myMethods = new MyUtilityMethods();
     
    			List<JPanel> lstPanel = (List<JPanel>) myMethods.createTabPanel(fc.getSelectedFile());
    			myMethods.createJTabbed(lstPanel, fc.getSelectedFile());
    			for (JPanel p : lstPanel) {
    				System.out.println(p.getName());
    			}
    		} else if (returnVal == JFileChooser.CANCEL_OPTION) {
    			//if you cancel
    			System.out.println("You chose to cancel this action ");	
    		}
    	}
    Il y a sans doute des truc pas très logique ou plus simple peut-être, alors n'hésitez pas à me le dire

    Merci Beaucoup Pour Vos Aides

  2. #2
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 213
    Points : 96
    Points
    96
    Par défaut
    Ce dont je suis sûr c'est que ce code récupère le bon fichier :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    System.out.println(excelFile.getName();
    wb = new XSSFWorkbook(excelFile.getName());
    Il récupère bien le bon fichier qui lui-même n'est évidement pas protéger.
    Cependant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    List<JPanel> lstPanel = (List<JPanel>) myMethods.createTabPanel(fc.getSelectedFile());
    Là je suis pas sur de m'y prendre correctement. La méthode createTabPanel retourne un panel par feuille Excel normalement, donc on doit bien récupérer une liste de panel...
    De-plus j'ai un warning qui dit :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Type safety: Unchecked cast from JComponent to List<JPanel>
    Seulement je pense pas avoir d'autre choix...
    Merci encore...

  3. #3
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 213
    Points : 96
    Points
    96
    Par défaut
    Voici une amélioration des méthode createJTabbedPane et createTabPanel
    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
     
    /**
             * Create  tabs based on file and panel 
             * 
             * @param tabPanel
             * @param file
             * @return
             */
    	public JTabbedPane createJTabbed(File file) {
     
    		JTabbedPane tabbedPane = new JTabbedPane();
     
    		List<JPanel> lstPanel = createTabPanel(file);
    		for (JPanel panel : lstPanel) {
    			tabbedPane.addTab
    			(
    				panel.getName(), //tab name 
    				null, //tab icon
    				panel, //Tabs panel for the JTable 
    				panel.getToolTipText() //tab tool tip text
    			);
    		}
    		return tabbedPane;
    	}
     
    	/**
             * Create a tab panel by excel feel
             * 
             * @param fileName
             * @param excelFile
             * @return
             */
    	public List<JPanel> createTabPanel(File excelFile) {
    		JTable spreadsheet = new JTable();
    		JPanel panel = null;
    		List<JPanel> lstPanel = null;
    		XSSFWorkbook wb;
    		XSSFSheet sheet;
     
    		try {
    			wb = new XSSFWorkbook(excelFile.getName());
    			//Get the sheet number
    			int nbFeuilles = wb.getNumberOfSheets();
    			for (int i = 0; i < nbFeuilles; i++) {
    				sheet = wb.getSheetAt(i);
    				//Create one JTable by excel feel
    				spreadsheet = createJTableWithExcel(excelFile, i);
     
    				spreadsheet.setFont(new Font(Font.SERIF, Font.PLAIN, 10));
    				JScrollPane elevator = new JScrollPane();
    				elevator.setViewportView(spreadsheet);
    				//Create a panel by excel feel number
    				panel = new JPanel();
    				panel.setBorder(BorderFactory.createTitledBorder(sheet.getSheetName()));
    				panel.setBackground(Color.LIGHT_GRAY);
    				panel.add(elevator);
     
    				lstPanel.add(panel);
    			}
    			wb.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return lstPanel;
    	}
    Et du coup de l'autre côté :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    	//if you validate
    	MyUtilityMethods myMethods = new MyUtilityMethods();
     
    	myMethods.createJTabbed(fc.getSelectedFile());
    	//for (JPanel p : lstPanel) {
    		System.out.println(fc.getSelectedFile().getName());
    	//}
    ...
    Voilà qui est un peu plus logique mais le message est toujours :
    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
     
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Zip File is closed
    	at org.apache.poi.openxml4j.util.ZipFileZipEntrySource.getEntries(ZipFileZipEntrySource.java:45)
    	at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:180)
    	at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:696)
    	at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:230)
    	at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:188)
    	at org.apache.poi.POIXMLDocument.openPackage(POIXMLDocument.java:85)
    	at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:319)
    	at EVENT.MyUtilityMethods.createTabPanel(MyUtilityMethods.java:72)
    	at EVENT.MyUtilityMethods.createJTabbed(MyUtilityMethods.java:44)
    	at EVENT.MyActionEvent.btnLoad_click(MyActionEvent.java:67)
    	at EVENT.MyActionEvent.actionPerformed(MyActionEvent.java:34)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Merci encore pour vos aides

  4. #4
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 213
    Points : 96
    Points
    96
    Par défaut
    Il n'y a rien à faire, ça ne fonctionne toujours pas

    Some helps please

  5. #5
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    Ce serait bien utile que tu nous montres ton dernier code complet, et non des bribes disparates

    Je ne sais pas pourquoi tu obtiens cette exception : quel version de POI utilises-tu ? Ce fichier est-il accèdé de manière exclusive par le code que tu montres et via un clic sur le bouton impliqué dans la stacktrace que tu montres ?

    Sinon, il y une chose qui m'étonne, c'est qu'il n'y a pas de méthode close() pour la classe org.apache.poi.xssf.usermodel.XSSFWorkbook. Donc le code que tu montres ne devrait même pas compiler. Il faudrait par exemple écrire wb.getPackage().close().
    Par ailleurs, le constructeur avec String est déprécié : ce serait mieux que tu n'utilises pas.

    Mais surtout, pourquoi ouvres-tu le fichier plusieurs fois, en même temps ? C'est inutile, sans parler des risques d'incohérences selon l'implémentation. Passe directement le sheet à la méthode createJTableWithExcel().
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  6. #6
    Membre régulier
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2016
    Messages
    213
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2016
    Messages : 213
    Points : 96
    Points
    96
    Par défaut
    Je vois ce que tu veux dire mais comment l'appliquer ?
    Voici mon nouveau code en essayant de faire ce que tu me suggère :
    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
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
     
    package EVENT;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.swing.BorderFactory;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
     
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    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 IHM.IhmConverter;
     
    /**
     * Some utility methods for the application
     * 
     * @author t0163126
     */
    public class UtilityMethods {
     
    	private static File file;
    	private static  final XSSFWorkbook wb = new XSSFWorkbook(file);
    // le new XSSFWorkbook(file); pose problème.
    	private static XSSFSheet sheet;
    	private static XSSFCell cell;
    	private static XSSFRow row;
     
     
    	/**
             * Create tabs based on file and panel
             * 
             * @param tabPanel
             * @param file
             * @return
             */
    	public static JTabbedPane createJTabbed(File file) {
     
    		JTabbedPane tabbedPane = new JTabbedPane();
     
    		List<JPanel> lstPanel = createTabPanel(file);
    		for (JPanel panel : lstPanel) {
    			tabbedPane.addTab(panel.getName(), // tab name
    					null, // tab icon
    					panel, // Tabs panel for the JTable
    					panel.getToolTipText() // tab tool tip text
    					);
    		}
    		return tabbedPane;
    	}
     
    	/**
             * Create a tab panel by excel feel
             * 
             * @param fileName
             * @param excelFile
             * @return
             */
    	public static List<JPanel> createTabPanel(File file) {
    		JTable spreadsheet = new JTable();
    		JPanel panel;
    		List<JPanel> lstPanel = new ArrayList<JPanel>();
     
    		try {
    			// Get the sheet number
    			int nbFeuilles = wb.getNumberOfSheets();
    			for (int i = 0; i < nbFeuilles; i++) {
    				sheet = wb.getSheetAt(i);
    				// Create one JTable by excel feel
    				spreadsheet = createJTableWithExcel(excelFile, i);
     
    				spreadsheet.setFont(new Font(Font.SERIF, Font.PLAIN, 10));
    				JScrollPane elevator = new JScrollPane();
    				elevator.setViewportView(spreadsheet);
    				// Create a panel by excel feel number
    				panel = new JPanel();
    				panel.setBorder(BorderFactory.createTitledBorder(sheet
    						.getSheetName()));
    				panel.setBackground(Color.LIGHT_GRAY);
    				panel.add(elevator);
     
    				lstPanel.add(panel);
    			}
    			wb.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return lstPanel;
    	}
     
    	/**
             * Create a JTable depending on the file and the entry sheet number
             * 
             * @param file
             * @param numSheet
             * @return
             */
    	public static JTable createJTableWithExcel(int numSheet) {
    		// Create new table
    		JTable table = new JTable();
    		// Reading the excel file
    		try {
    			// Get the contents of the excel file according to the sheet number
    			sheet = wb.getSheetAt(numSheet);
     
    			// Count the line number
    			int nbRows = sheet.getLastRowNum();
    			// Count the column number
    			int nbColumns = numberMaxColumn(sheet);
     
    			System.out.println("In the sheet " + sheet.getSheetName()
    					+ " there are " + nbRows + " lines and " + nbColumns
    					+ " columns");
     
    			// Create new object array
    			Object[][] obj = new Object[nbRows][nbColumns];
     
    			// Array header
    			String[] title = new String[nbColumns];
    			for (int i = 0; i < nbColumns; i++) {
    				title[i] = "#" + i;
    			}
     
    			// Browsing the sheet and retrieves the lines one by one
    			for (int rowContent = 0; rowContent < nbRows; rowContent++) {
    				row = sheet.getRow(rowContent);
     
    				// Browsing the line and retrieves the columns
    				if (row != null) {
    					for (int columnContent = 0; columnContent < nbColumns; columnContent++) {
    						// Retrieves the cell and this value
    						cell = row.getCell((short) columnContent);
    						Object value = contentCell(cell);
    						// System.out.println(value.toString());
    						obj[rowContent][columnContent] = value;
    					}
    				}
    			}
     
    			wb.close();
    			table.setModel(new DefaultTableModel(obj, title));
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return table;
    	}
     
    	/**
             * The cell can contain different type of value that should be specifically
             * recovered
             * 
             * @param cell
             * @return
             */
    	private static Object contentCell(XSSFCell c) {
    		Object value = null;
     
    		if (c == null) {
    			value = "";
    		} else if (c.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
    			value = c.getBooleanCellValue();
    		} else if (c.getCellType() == XSSFCell.CELL_TYPE_ERROR) {
    			value = c.getErrorCellValue();
    		} else if (c.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
    			value = c.getCellFormula();
    		} else if (c.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
    			value = c.getNumericCellValue();
    		} else if (c.getCellType() == XSSFCell.CELL_TYPE_STRING) {
    			value = c.getStringCellValue();
    		}
    		return value;
    	}
     
    	/**
             * Retrieves the maximum number of column. If a line has 2 empty boxes at
             * the end , they are not taken into account. So to retrieve the number of
             * columns to initialize our table we must browse all lines
             * 
             * @param sheet
             * @return
             */
    	private static int numberMaxColumn(XSSFSheet st) {
    		int r = st.getLastRowNum();
    		int max = 0;
    		int s = 0;
    		while (s < r) {
    			if (st.getRow(s) != null) {
    				int c = st.getRow(s).getLastCellNum();
    				if (c > max) {
    					max = c;
    				}
    			}
    			s++;
    		}
    		return max + 1;
    	}
     
    	/**
             * Closing the application
             */
    	public static void closeApplication() {
    		IhmConverter ihm = IhmConverter.getInstance();
     
    		Object[] options = { 
    			"Yes, please", "Oops no!" 
    		};
    		int retour = JOptionPane.showOptionDialog(ihm, Final.getMsgExit(),
    				Final.getMsgExitTitle(), JOptionPane.YES_NO_OPTION,
    				JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
     
    		if (retour == JOptionPane.YES_OPTION) {
    			ihm.setVisible(false);
    			ihm.dispose();
    			System.exit(0);
    		} else if (retour == JOptionPane.NO_OPTION) {
    			// do nothing
    		}
    	}
    }
    Je le test comme ceci :
    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
     
    private void btnLoad_click() 
    	{
    		JFileChooser fc = new MyFileChooser();
     
    		//Open the dialog box
    		int returnVal = fc.showOpenDialog(null);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			//if you validate
    			JTabbedPane lstPanels = UtilityMethods.createJTabbed(fc.getSelectedFile());
    			//for (JTabbedPane p : myMethods) {
    			for (Iterator<JTabbedPane> it = ((List<JTabbedPane>) lstPanels).iterator(); it.hasNext();) {
    				System.out.println(it.next());
    			}
    		} else if (returnVal == JFileChooser.CANCEL_OPTION) {
    			//if you cancel
    			System.out.println("You chose to cancel this action ");	
    		}
    	}
    Voilà tout...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Apache POI] Créer group dans excel
    Par Mattorre dans le forum Documents
    Réponses: 1
    Dernier message: 11/05/2011, 21h41
  2. problème création rapport excel avec apache poi
    Par jakcam dans le forum API standards et tierces
    Réponses: 7
    Dernier message: 07/10/2009, 14h07
  3. Réponses: 1
    Dernier message: 22/06/2009, 14h26
  4. [XL-2007] Type de fichier pour Excel 2007: xls, xlsx, xlsm ou xlsb ?
    Par APE3392 dans le forum Excel
    Réponses: 2
    Dernier message: 18/06/2009, 18h02
  5. Réponses: 0
    Dernier message: 27/10/2008, 14h58

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