Come leggere un file Excel con Java
1.220 visiteVediamo, in questo articolo, come leggere un file Excel con Java utilizzando la libreria jexcelapi che è possibile scaricare la libreria da questo link: http://jexcelapi.sourceforge.net/
Il primo passaggio fondamentale per poter leggere un file Excel è quello di creare un “Workbook“.
1 |
Workbook workbook = Workbook.getWorkbook(new File("nome_file.xls")); |
Una volta che si ha l’oggetto sopra citato,è possibile fare riferimento al foglio in 2 modi:
1 2 |
Sheet sheet = workbook.getSheet(0); Sheet sheet = workbook.getSheet("nome_foglio"); |
Nel primo caso è possibile cercare il foglio in ordine crescente,nel secondo caso si ha un accesso diretto con il nome del foglio.
Ora vediamo come poter accedere direttamente al contenuto excel delle celle.
1 2 3 4 5 6 7 |
Cell a = sheet.getCell(0,0); Cell b = sheet.getCell(1,1); Cell c = sheet.getCell(2,1); String stringa1 = a.getContents(); String stringa2 = b.getContents(); String stringa3 = c.getContents(); |
Questo è l’approccio più veloce ma meno cosigliato.
Altrimenti possiamo usare:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
String stringa = null; double numero = 0; Date data = null; Cell a = sheet.getCell(0,0); Cell b = sheet.getCell(1,1); Cell c = sheet.getCell(2,1); if (c.getType() == CellType.DATE) { DateCell dc = (DateCell) c; data = dc.getDate(); } if (a.getType() == CellType.LABEL) { LabelCell lc = (LabelCell) a; stringa = lc.getString(); } if (b.getType() == CellType.NUMBER) { NumberCell nc = (NumberCell) b; numero = nc.getValue(); } |
Il metodo getCell vuole come primo parametro il numero della colonna,mentre nel secondo quello della riga.
1 |
getCell(int column, int row) |
Una volta finito il processo, si richiama il metodo:
1 |
workbook.close(); |
Metodi utili per la lettura:
1) Far restituire il numero delle righe presenti nel foglio scelto:
1 |
int totaleRighe = sheet.getRows(); |
2) Permette di creare una lista di array di Cell.
1 2 3 4 5 |
List listaCellRighe = new ArrayList(); for(int i=0;i<totaleRighe;i++){ listaCellRighe.add(sheet.getRow(i)); } |
Cosi da poter lavorare direttamente sulle celle. Per esempio:
1 2 3 4 |
for(int j=0;j<listaCellRighe.size();j++){ Cell [] tmpCell = listaCellRighe.get(j); String risultato = tmpCell[0].getContents() + tmpCell[1].getContents(); } |