Tutorial Apache POI: creiamo un file Excel

Tutorial Apache POI: creiamo un file Excel

In questo articolo vedremo come creare un file Excel utilizzando la libreria Apache POI.Il primo passo è quello di creare un Workbook, per poterlo istanziare dobbiamo decidere quale formato di Excel, cioè quale estensione avrà il nostro file. Se vogliamo un file .xlsx dobbiamo creare un Workbook di tipo XSSF (XSSFWorkbook) altrimenti per .xls il Workbook sarà di tipo HSSF (HSSFWorkbook):[java] XSSFWorkbook wb = new XSSFWorkbook(); [/java] oppure[java] HSSFWorkbook wb = new HSSFWorkbook(); [/java]

Tutorial Apache POI: scriviamo e leggiamo un documento Word
Integrazione di Apache Tomcat su Apache HTTP Server
Apache MyFaces: un’implementazione Open Source delle specifiche JSF

In questo articolo vedremo come creare un file Excel utilizzando la libreria Apache POI.

Il primo passo è quello di creare un Workbook, per poterlo istanziare dobbiamo decidere quale formato di Excel, cioè quale estensione avrà il nostro file. Se vogliamo un file .xlsx dobbiamo creare un Workbook di tipo XSSF (XSSFWorkbook) altrimenti per .xls il Workbook sarà di tipo HSSF (HSSFWorkbook):

XSSFWorkbook wb = new XSSFWorkbook();

oppure

HSSFWorkbook wb = new HSSFWorkbook();

Altrimenti, in maniera più elegante, possiamo utilizzare il componente SS, che offre una interfaccia Workbook che è implementata da entrambe le due classi XSSF e HSSF, per cui possiamo scrivere:

Workbook wb = new XSSFWorkbook();

oppure

Workbook wb = new HSSFWorkbook();

Utilizziamo nel resto dell’articolo, questo ultimo approccio, andremo cioè ad utilizzare le interfacce definite nel package org.apache.poi.ss.usermodel. Utilizzeremo congiuntamente una classe Helper (CreationHelper) che si occupa di istanziare la giusta classe a seconda del Workbook utilizzato (HSSF e XSSF).

Proviamo a creare dei fogli, utilizzando il metodo createSheet():

Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");

Creiamo poi una riga e delle celle (le righe e le celle partono da posizione 0):

//Otteniamo una istanza di CreationHelper del nostro Workbook
CreationHelper createHelper = wb.getCreationHelper();
// Creiamo una riga alla posizione 0
Row row = sheet.createRow((short)0);
// Creiamo una cella e inseriamo un valore
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Possiamo creare una cella e inserirci un valore in una sola riga di codice
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);

Per vedere l’output generato, scriviamo il file:

FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

In questo caso abbiamo scritto un file di tipo xls, se volessimo scriverlo in .xlsx basta cambiare l’estensione del file (workbook.xlsx). Se stiamo usando Eclipse il file verrà scritto nella directory radice del nostro progetto.

Proviamo ora ad allineare un testo in una cella:

public static void main (String[] args) throws Exception{
	Workbook wb = new HSSFWorkbook(); //or new HSSFWorkbook();

        Sheet sheet = wb.createSheet();
	Row row = sheet.createRow((short) 2);
        //Settiamo l'altezza della riga (in punti)
        row.setHeightInPoints(30);

        //testiamo i vari allineamenti sia orizzontali che verticali
        createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
        createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
        createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
        createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
        createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
        createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
        createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);

        FileOutputStream fileOut = new FileOutputStream("align-test.xls");
        wb.write(fileOut);
        fileOut.close();

}

private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {
        Cell cell = row.createCell(column);
        cell.setCellValue("Align It");
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(halign);
        cellStyle.setVerticalAlignment(valign);
        cell.setCellStyle(cellStyle);
    }

Proviamo ora a creare dei bordi nelle nostre celle:

Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");

    // Creiamo una riga
    Row row = sheet.createRow(1);

    // Creiamo una cella col valore 4 inserito
    Cell cell = row.createCell(1);
    cell.setCellValue(4);

    // Settiamo i bordi della cella, possiamo scegliere la posizione, il colore e lo stile del bordo
    CellStyle style = wb.createCellStyle();
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.RED.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.BLUE.getIndex());
    style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
    cell.setCellStyle(style);

    // scriviamo il file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

Proviamo ora a scrivere dei valori nelle celle e poi a leggerli:


public static void main (String[] args) throws Exception{
	Workbook wb = new HSSFWorkbook(); //or new HSSFWorkbook();

        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow((short)2);
        row.createCell(0).setCellValue(1.1);
        row.createCell(1).setCellValue(new Date());
        row.createCell(2).setCellValue(Calendar.getInstance());
        row.createCell(3).setCellValue("a string");
        row.createCell(4).setCellValue(true);
        row.createCell(5).setCellType(HSSFCell.CELL_TYPE_ERROR);
        row.createCell(6).setCellValue(new Date());

        //Formattiamo la cella 6 come Data
        CreationHelper createHelper = wb.getCreationHelper();
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd/mm/yy hh:mm"));
        row.getCell(6).setCellStyle(cellStyle);

        Sheet sheet1 = wb.getSheetAt(0);
        //Iteriamo lungo le righe e le celle del foglio Excel
    	for (Row row1 : sheet1) {
    	     for (Cell cell1 : row1) {
		switch(cell1.getCellType()) {
	    	       case Cell.CELL_TYPE_STRING:
	    	        System.out.println(cell1
                        .getRichStringCellValue().getString());
	    	        break;
	    	      case Cell.CELL_TYPE_NUMERIC:
	    	        if(DateUtil.isCellDateFormatted(cell1)) {
	    	          System.out.println(cell1.getDateCellValue());
	    	        } else {
	    	          System.out.println(cell1.getNumericCellValue());
	    	        }
	    	        break;
	    	      case Cell.CELL_TYPE_BOOLEAN:
	    	        System.out.println(cell1.getBooleanCellValue());
	    	        break;
	    	      case Cell.CELL_TYPE_FORMULA:
	    	        System.out.println(cell1.getCellFormula());
	    	        break;
	    	      default:
	    	        System.out.println();
	    		}
	    	}
	    		}
        // Scriviamo il file
        FileOutputStream fileOut = new FileOutputStream("read-test.xls");
        wb.write(fileOut);
        fileOut.close();
	}

COMMENTS

WORDPRESS: 2
  • comment-avatar
    Pasquale 9 anni ago

    Complimenti per il tutorial, veramente chiarissimo.
    Potrebbe essere utile anche un articolo simile sulla lettura di un file xls per poterne ricavare e elaborare le informazioni.
    Pasquale

  • comment-avatar
    Andrea Romiti 2 anni ago

    Buonasera, sono un neofita in java,

    mi da errore la stringa ” …Sheet sheet = wb.createSheet(“new sheet”); …..”
    Le librerie java installate sono
    commons-collections4-4.1.jar
    poi-3.17.jar
    poi-ooxml-3.17.jar
    poi-ooxml-schemas-3.17.jar
    cosa manca?