Creare file Excel in Java con Apache POI

Mattepuffo's logo
Creare file Excel in Java con Apache POI

Creare file Excel in Java con Apache POI

Apache POI è una libreria per Java per la manipolazione dei file di MS Office.

Oggi vediamo un esempio su come creare un file Excel.

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

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
            <type>jar</type>
        </dependency>

L'esempio che vedremo è molto semplicisitico ovviamente, ma può essere preso come base per qualcosa di più interessante:

public class Main {

    public static void main(String[] args) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet spreadsheet = workbook.createSheet("UTENTI");
        Map<String, Object[]> empinfo = new TreeMap<>();
        empinfo.put("1", new Object[]{"UTENTE ID", "NOME", "EMAIL"});
        for (int i = 2; i < 6; i++) {
            empinfo.put(String.valueOf(i), new Object[]{
                String.valueOf(i - 1), "UT " + (i - 1),
                "email@utente" + (i - 1) + ".com"
            });
        }
        Set keyid = empinfo.keySet();
        int rowid = 0;
        XSSFRow row;
        for (String key : keyid) {
            row = spreadsheet.createRow(rowid++);
            Object[] objectArr = empinfo.get(key);
            int cellid = 0;
            for (Object obj : objectArr) {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue((String) obj);
            }
        }
        try (FileOutputStream out = new FileOutputStream(new File("file.xlsx"))) {
            workbook.write(out);
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Ripeto, sicuramente è un codice migliorabile, ma possiamo usarlo come base di partenza!

Enjoy!


Condividi

Commentami!