L'exportation de données vers des feuilles de calcul Excel est une fonctionnalité récurrente dans les applications d'entreprise développées en Java. Deux bibliothèques se distinguent historiquement pour accomplir cette tâche : Apache POI, la solution la plus complète gérant les formats modernes, et JXL (Java Excel API), une alternative plus légère limitée au format .xls.
1. Mise en œuvre avec Apache POI
Apache POI est le framework standard pour manipuler les documents Microsoft Office. Il propose les composants HSSF pour le format Excel 97-2003 (.xls) et XSSF pour le format OOXML (.xlsx).
Configuration Maven
Ajoutez les dépendances suivantes à votre fichier pom.xml pour supporter les deux formats :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Modèle de données
public class RapportActivite {
private String departement;
private String realisations;
private String previsions;
public RapportActivite(String departement, String realisations, String previsions) {
this.departement = departement;
this.realisations = realisations;
this.previsions = previsions;
}
// Getters et Setters
public String getDepartement() { return departement; }
public void setDepartement(String departement) { this.departement = departement; }
public String getRealisations() { return realisations; }
public void setRealisations(String realisations) { this.realisations = realisations; }
public String getPrevisions() { return previsions; }
public void setPrevisions(String previsions) { this.previsions = previsions; }
}
Logique d'exportation
Cet exemple utilise Spring MVC pour générer et envoyer le fichier directement dans la réponse HTTP.
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
@RestController
public class ExportController {
@GetMapping("/export/poi")
public void genererExcel(HttpServletResponse response) throws IOException {
List<RapportActivite> donnees = Arrays.asList(
new RapportActivite("DSI Paris", "Migration Cloud terminée", "Optimisation SQL"),
new RapportActivite("DSI Lyon", "Déploiement Mobile", "Tests de charge")
);
try (HSSFWorkbook classeur = new HSSFWorkbook()) {
HSSFSheet feuille = classeur.createSheet("Rapport Hebdo");
// Style d'alignement pour le titre
CellStyle styleTitre = classeur.createCellStyle();
styleTitre.setAlignment(HorizontalAlignment.CENTER);
styleTitre.setVerticalAlignment(VerticalAlignment.CENTER);
// Création du titre fusionné
HSSFRow ligneTitre = feuille.createRow(0);
HSSFCell celluleTitre = ligneTitre.createCell(0);
celluleTitre.setCellValue("Synthèse des Activités Hebdomadaires");
celluleTitre.setCellStyle(styleTitre);
feuille.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
// En-têtes de colonnes
HSSFRow entete = feuille.createRow(1);
String[] colonnes = {"Département", "Réalisations", "Objectifs Suivants"};
for (int i = 0; i < colonnes.length; i++) {
entete.createCell(i).setCellValue(colonnes[i]);
}
// Remplissage des données
int indexLigne = 2;
for (RapportActivite item : donnees) {
HSSFRow ligne = feuille.createRow(indexLigne++);
ligne.createCell(0).setCellValue(item.getDepartement());
ligne.createCell(1).setCellValue(item.getRealisations());
ligne.createCell(2).setCellValue(item.getPrevisions());
}
// Configuration de la réponse HTTP
String nomFichier = "Rapport_Export.xls";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(nomFichier, "UTF-8"));
try (OutputStream out = response.getOutputStream()) {
classeur.write(out);
}
}
}
}
2. Utilisation de JXL (JExcelAPI)
JXL est une bibliothèque plus ancienne, appréciée pour sa simplicité. Notez qu'elle ne supporte que le format .xls (Excel 95-2003).
Configuration Maven
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Modèle pour les ressources
public class MembreEquipe {
private String matricule;
private String nom;
private String role;
public MembreEquipe(String matricule, String nom, String role) {
this.matricule = matricule;
this.nom = nom;
this.role = role;
}
// Getters...
public String getMatricule() { return matricule; }
public String getNom() { return nom; }
public String getRole() { return role; }
}
Génération de fichier avec JXL
L'approche suivante montre comment créer un fichier localement avant de le diffuser.
import jxl.Workbook;
import jxl.write.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@RestController
public class JxlExportController {
@GetMapping("/export/jxl")
public void exporterAvecJxl() throws Exception {
List<MembreEquipe> staff = new ArrayList<>();
staff.add(new MembreEquipe("EMP001", "Jean Dupont", "Architecte"));
File dossier = new File("C:/exports/");
if (!dossier.exists()) dossier.mkdirs();
File fichierExcel = new File(dossier, "Staff_Equipe.xls");
WritableWorkbook workbook = Workbook.createWorkbook(fichierExcel);
try {
WritableSheet feuille = workbook.createSheet("Liste Personnel", 0);
// Formatage de l'en-tête
WritableFont policeEntete = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
WritableCellFormat formatEntete = new WritableCellFormat(policeEntete);
formatEntete.setAlignment(Alignment.CENTRE);
// Ajout des titres de colonnes
String[] titres = {"ID", "Nom Complet", "Fonction"};
for (int i = 0; i < titres.length; i++) {
feuille.addCell(new Label(i, 0, titres[i], formatEntete));
}
// Insertion des données
int numLigne = 1;
for (MembreEquipe membre : staff) {
feuille.addCell(new Label(0, numLigne, membre.getMatricule()));
feuille.addCell(new Label(1, numLigne, membre.getNom()));
feuille.addCell(new Label(2, numLigne, membre.getRole()));
numLigne++;
}
workbook.write();
} finally {
workbook.close();
}
}
}
Points de comparaison
- Apache POI : Plus puissant, supporte le format .xlsx, activement mainteun, mais consomme plus de mémoire sur de gros volumes.
- JXL : Plus rapide et moins gourmand en ressources, mais obsolète pour les versions récentes d'Excel et ne gère pas le format XML (.xlsx).