Creare file Excel con Java

Mattepuffo's logo
Creare file Excel con Java

Creare file Excel con Java

Creare file Excel con Java è più facile di quello che sembra.

Vi posto il mio caso reale, e cioè l'esportazione di una JTable in formato Excel.

Avevo già parlato di come esportare una JTable, ma questo metodo è nettamente migliore.

Il motivo è che creeremo un file xls ben formato usando una libreria apposita: JExcelApi.

Scaricate la libreria e aggiuntete il jar nella vostra applicazione.

Se tutto è andato bene potete importare i package jxl.*.

A questo punto creiamo una classe per fare tutte le operazioni del caso:

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExportXls {

    private WritableCellFormat timesBold;
    private WritableCellFormat times;

    public void create(String inputFile) throws IOException, WriteException {
        File file = new File(inputFile);
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("it", "IT"));

        WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
        workbook.createSheet("Book", 0);
        WritableSheet excelSheet = workbook.getSheet(0);

        createLabel(excelSheet);
        createContent(excelSheet);

        workbook.write();
        workbook.close();
    }

    private void createLabel(WritableSheet sheet) throws WriteException {
        WritableFont timesFontBold = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD);
        timesBold = new WritableCellFormat(timesFontBold);
        timesBold.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(timesBold);
        cv.setAutosize(true);

        addCaption(sheet, 0, 0, "ID");
        addCaption(sheet, 1, 0, "TITLE");
        addCaption(sheet, 2, 0, "AUTHOR");
        addCaption(sheet, 3, 0, "EDITOR");
        addCaption(sheet, 4, 0, "PRICE");
        addCaption(sheet, 5, 0, "ISBN");
        addCaption(sheet, 6, 0, "NOTE");
    }

    private void addCaption(WritableSheet sheet, int column, int row, String s) throws RowsExceededException, WriteException {
        Label label = new Label(column, row, s, timesBold);
        sheet.addCell(label);
    }

    private void createContent(WritableSheet sheet) throws WriteException, RowsExceededException {
        WritableFont timesFont = new WritableFont(WritableFont.TIMES, 12);
        times = new WritableCellFormat(timesFont);
        times.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(times);
        cv.setAutosize(true);
        
        for (int i = 1; i < FormBook.getTable().getRowCount(); i++) {
            for (int j = 0; j < FormBook.getTable().getColumnCount(); j++) {
                Label lb = new Label(j, i, (String) (FormBook.getTable().getValueAt(i, j)), times);
                sheet.addCell(lb);
            }
        }
    }
}

Il metodo write è quello principale; richiede una String come parametro e corrisponde al percorso di salvataggio del file.

WorkbookSettings server per settare alcune impostazioni generali, mentre WritableWorkbook e WritableSheet settano il foglio di lavoro.

Poi ci sono due metodi: createLabel e createContent creati da me; entrambi richiedono come parametri lo sheet da usare.

Con il primo creo tutta la intestazione formattando le celle in grassetto.

Con il secondo invece creo il contenuto estrapolandonolo dalla JTable.

CellView serve per settare le varie impostazioni delle celle.

Label server per scriver il contenuto dentro le celle.

Il costruttore che ho usato prevede di passare 4 argomenti: numero colonna, numero riga, contenuto, formato usato.

Notate bene che il primo ciclo for di createContent, che rappresenta il numero di righe, inizia da 1.

Questo perchè il conteggio di righe e colonne in Excel comincia da zero, e la riga 0 è occupata dall'intestazione.

Dopo aver lanciato quei due metodi scriviamo il file e lo chiudiamo.

Per uno studio più approfondito vi rimando alla Javadoc ufficiale.

A questo punto possiamo richiamare il file dentro un JFileChooser ad esempio:

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import jxl.write.WriteException;

public class FileChooserXls {

    private static File f = null;

    public void salva() throws IOException, WriteException {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Save XLS");
        fc.setApproveButtonText("Save");
        fc.setApproveButtonToolTipText("Approve file");

        FileFilter xlsFilter = new GenericFileFilter("File *.xls", "xls");
        fc.setFileFilter(xlsFilter);

        int returnVal = fc.showSaveDialog(fc);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            f = fc.getSelectedFile();
            FileFilter selectedFilter = fc.getFileFilter();
            if (f.getName().indexOf('.') == -1) {
                if (selectedFilter == xlsFilter) {
                    f = new File(f.getPath() + ".xls");
                } else {
                    f = new File(f.getPath() + ".xls");
                }
            }
            if (f.exists()) {
                String msg = MessageFormat.format("The entry ''{0}'' already exists.\nDo you want to replace it?", new Object[]{f});
                int r = JOptionPane.showConfirmDialog(null, msg, "Confirm", JOptionPane.YES_NO_OPTION);
                if (r == JOptionPane.NO_OPTION) {
                    return;
                }
            }
            ExportXls test = new ExportXls();
            test.create(f.toString());
        }
    }
}

Come stringa gli passiamo il file scelto nel JFC.

Come vedete la libreria è semplice da usare: ci sono parecchi metodo utili e sono facili da comprendere


Condividi

Commentami!