1. Dépendances Maven
Pour intégrer la génération de feuilles de calcul dans une application Spring Boot, il est nécessaire d'ajotuer les bibliothèques Apache POI au fichier pom.xml :
<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>
2. Implémentation du contrôleur
Le contrôleur suivant gère la requête HTTP, récupère une liste d'objets métier, utilise la réflexion pour mapper les données, et transmet le ficheir Excel généré au flux de sortie de la réponse.
package com.example.reporting.controller;
import com.example.reporting.model.Person;
import com.example.reporting.util.SpreadsheetBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("/report")
public class ExportController {
@GetMapping("/download")
public String generateSpreadsheet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
String baseName = "rapport_utilisateurs";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle cellStyle = buildCustomStyle(workbook);
HSSFSheet sheet = workbook.createSheet("Données");
try {
List<Person> records = fetchPersonList();
if (CollectionUtils.isNotEmpty(records)) {
String[] headers = {"Identifiant", "Nom complet", "Âge"};
SpreadsheetBuilder.createHeaderRow(workbook, sheet, headers);
Class<?> clazz = records.get(0).getClass();
Field[] classFields = clazz.getDeclaredFields();
for (int i = 0; i < records.size(); i++) {
HSSFRow currentRow = sheet.createRow(i + 1);
currentRow.setHeight((short) 400);
for (int j = 0; j < classFields.length; j++) {
classFields[j].setAccessible(true);
HSSFCell currentCell = currentRow.createCell(j);
Object val = classFields[j].get(records.get(i));
currentCell.setCellValue(Objects.toString(val, ""));
currentCell.setCellStyle(cellStyle);
}
}
} else {
SpreadsheetBuilder.appendEmptyMessage(workbook, sheet, "Aucune donnée disponible");
}
} catch (Exception ex) {
log.error("Échec lors de la création du fichier Excel :", ex);
SpreadsheetBuilder.appendEmptyMessage(workbook, sheet, "Erreur de traitement");
baseName = "erreur_generation";
}
SpreadsheetBuilder.writeToOutputStream(httpRequest, httpResponse, workbook, baseName);
return "Exportation terminée avec succès";
}
private List<Person> fetchPersonList() {
List<Person> dataset = new ArrayList<>();
dataset.add(new Person(1L, "Alice Martin", 28));
dataset.add(new Person(2L, "Bob Dupont", 34));
dataset.add(new Person(3L, "Claire Leroy", 22));
return dataset;
}
private HSSFCellStyle buildCustomStyle(HSSFSSFWorkbook wb) {
HSSFCellStyle style = wb.createCellStyle();
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
HSSFFont font = wb.createFont();
font.setColor(Font.COLOR_RED);
font.setFontName("Arial");
font.setFontHeightInPoints((short) 11);
style.setFont(font);
return style;
}
}
3. Clase utilitaire pour la construction du document
L'utilitaire suivant centralise la mise en forme des en-têtes, la gestion des messages d'erreur et l'encodage du nom de fichier selon le navigateur client.
package com.example.reporting.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
@Slf4j
public class SpreadsheetBuilder {
public static HSSFRow createHeaderRow(HSSFWorkbook wb, HSSFSheet sh, String[] titles) {
HSSFRow row = sh.createRow(0);
row.setHeight((short) 500);
HSSFFont font = wb.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 13);
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setFont(font);
for (int idx = 0; idx < titles.length; idx++) {
HSSFCell cell = row.createCell(idx);
cell.setCellValue(titles[idx]);
sh.setColumnWidth(idx, 5500);
cell.setCellStyle(style);
}
return row;
}
public static HSSFRow appendEmptyMessage(HSSFWorkbook wb, HSSFSheet sh, String msg) {
HSSFRow row = sh.createRow(0);
row.setHeight((short) 800);
sh.setColumnWidth(0, 8000);
HSSFCellStyle style = wb.createCellStyle();
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);
HSSFCell cell = row.createCell(0);
cell.setCellValue(msg);
cell.setCellStyle(style);
return row;
}
public static void writeToOutputStream(HttpServletRequest req, HttpServletResponse resp, HSSFWorkbook wb, String prefix) {
try {
int randomId = (int) (Math.random() * 9000 + 1000);
String fullName = prefix + "_" + randomId + ".xls";
if (isExplorerOrEdge(req)) {
fullName = URLEncoder.encode(fullName, "UTF-8");
} else {
fullName = new String(fullName.getBytes("UTF-8"), "iso-8859-1");
}
resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
resp.setHeader("Content-Disposition", "attachment;filename=" + fullName);
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);
try (OutputStream out = resp.getOutputStream()) {
wb.write(out);
out.flush();
}
} catch (IOException e) {
log.error("Erreur lors de l'écriture du flux de sortie :", e);
}
}
private static boolean isExplorerOrEdge(HttpServletRequest req) {
String agent = req.getHeader("User-Agent");
if (StringUtils.isBlank(agent)) {
return false;
}
String[] keywords = {"msie", "trident", "edge"};
for (String word : keywords) {
if (agent.toLowerCase().contains(word)) {
return true;
}
}
return false;
}
}