Leggere file Excel con Java e Apache POI

Mattepuffo's logo
Leggere file Excel con Java e Apache POI

Leggere file Excel con Java e Apache POI

Abbiamo già visto altre visto la libreria Apache POI, che ci consente di manipolare file MS Office in Java.

Oggi vediamo come leggere un file Excel.

Se usate Maven, aggiungete questo al file pom.xml:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

Compilate e vediamo l'esempio:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

public class Main {

    public static void main(String[] args) {
        try {
            String file = "test.xlsx";
            FileInputStream excelFile = new FileInputStream(new File(file));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet datatypeSheet = workbook.getSheetAt(0);
            Iterator iterator = datatypeSheet.iterator();
            while (iterator.hasNext()) {
                Row currentRow = iterator.next();
                Iterator cellIterator = currentRow.iterator();
                while (cellIterator.hasNext()) {
                    Cell currentCell = cellIterator.next();
                    if (currentCell.getCellTypeEnum() == CellType.STRING) {
                        System.out.print(currentCell.getStringCellValue() + "--");
                    } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                        System.out.print(currentCell.getNumericCellValue() + "--");
                    }
                }
                System.out.println();
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

}

L'esempio è abbastanza basico, ma comunque completo.

Iteriamo su tutte le righe del primo foglio; all'interno del primo while ne abbiamo un secondo per iterare su tutte le celle della riga corrente.

Enjoy!


Condividi

Commentami!