Annotation-Driven Excel/CSV Processing in Spring Boot with dev-excel Library
This tutorial demonstrates how to use the dev-excel library to generate and read Excel and CSV files in Spring Boot 3.x applications through annotation-driven models, covering multi-sheet reading, row filtering, JPA query-driven exports, formula columns, and streaming large datasets with SXSSF.
Reading font
Projects often need to generate and read Excel/CSV files for reports, data imports, and batch processing. Manual parsing is complex, error-prone, and hard to maintain across file versions. The dev-excel library, built on Apache POI 5.x, simplifies this with annotation-driven models for Spring Boot 3.x (Java 17+).
Library Modules
common-spreadsheet (Utility): Shared annotations, utilities, and exception handling for the two core libraries.
generator-excel (Utility): Exports annotated Java objects to .xls, .xlsx, and CSV.
read-excel (Utility): Reads .xls, .xlsx, and CSV files into annotated Java objects.
report-excel (Integration Test): Static data and Excel/CSV read tests with REST endpoints.
report-excel-jpa (Integration Test): Database-driven report generation with charts, pivot tables, and large data handling.
report-excel-multiple-datasource (Integration Test): Generates multi-sheet Excel reports from multiple data sources.
Setup
Add dependencies:
<!-- Excel / CSV Generator -->
<dependency>
<groupId>com.github.bld-commons.excel</groupId>
<artifactId>generator-excel</artifactId>
<version>5.2.1</version>
</dependency>
<!-- Excel / CSV Reader -->
<dependency>
<groupId>com.github.bld-commons.excel</groupId>
<artifactId>read-excel</artifactId>
<version>5.2.1</version>
</dependency>Enable annotations with a configuration class:
@Configuration
@EnableExcelGenerator
@EnableExcelRead
public class ExcelCsvConfig {}Reading Excel/CSV Files
Supports multi-sheet reading, index-based sheet mapping, custom row filtering, and Bean Validation.
Data Model
public class EmployeeRow implements RowSheetRead {
@ExcelReadColumn("编号")
private Integer id;
@ExcelReadColumn("姓名")
private String name;
@ExcelReadColumn("部门")
private String department;
@ExcelReadColumn("薪水")
private Double salary;
@ExcelReadColumn("入职时间")
private Calendar startDate;
}Sheet Entity
@ExcelReadSheet(startRow = 0)
public class EmployeeSheet extends SheetRead<EmployeeRow> {
public EmployeeSheet(String name) { super(name); }
}startRow = 0indicates the header is on row 0 (zero-based).
Reading Code
@Resource
private ReadExcel readExcel;
@Test
public void testReadExcel() throws Exception {
byte[] fileBytes = new FileSystemResource("f:/employee.xlsx").getContentAsByteArray();
ExcelRead excelRead = new ExcelRead();
excelRead.setReportExcel(fileBytes);
excelRead.setExcelType(ExcelType.XLSX);
excelRead.addSheetConvertion(EmployeeSheet.class, "Employees");
excelRead = readExcel.convertExcelToEntity(excelRead);
List<EmployeeRow> rows = excelRead.getSheet(EmployeeSheet.class, "Employees").getRows();
rows.forEach(System.out::println);
}Core Read APIs
ReadExcel – Read Excel files. Method: convertExcelToEntity(ExcelRead) – Parses Excel and populates all registered sheetRead instances.
ReadCsv – Read CSV files. Method: convertCsvToEntity(CsvRead<T>, Class<T>) – Parses CSV and fills row data of type T into CsvRead.
Row Filtering
Override filtered in the sheet class:
@ExcelReadSheet
public class DataMeteoSheet extends SheetRead<EmployeeRow> {
@Override
protected boolean filtered(EmployeeRow row) {
boolean result = ...;
return result;
}
}Reading CSV with Validation
@CsvSettings(delimiter = ',', skipHeaderRecord = true)
public class Employee implements RowSheetRead {
@NotBlank
private String name;
@NotNull
@Positive
private Integer age;
}
@Test
public void testReadCsv() throws Exception {
byte[] csv = IOUtils.toByteArray(new FileInputStream("f:/employee.csv"));
CsvRead<Employee> csvRead = new CsvRead<>();
csvRead.setCsv(csv);
readCsv.convertCsvToEntity(csvRead, Employee.class);
System.out.println("Rows: " + csvRead.getRows());
}Generating Excel/CSV Files
Supports static data, JPA query-driven data, charts, pivot tables, images, subtotals, conditional formatting, and titles.
Data Model
public class EmployeeRow implements RowSheet, CsvRow {
@ExcelColumn(name = "编号", index = 1)
@ExcelCellLayout(autoSizeColumn = true, rgbForeground = {@ExcelRgbColor(red = 18, green = (byte)167, blue = 61)}, rgbFont = {@ExcelRgbColor})
private Integer id;
@ExcelColumn(name = "姓名", index = 2)
@ExcelCellLayout(autoSizeColumn = true)
private String name;
@ExcelColumn(name = "部门", index = 3)
@ExcelCellLayout(autoSizeColumn = true)
private String department;
@ExcelColumn(name = "薪水", index = 4)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT, precision = 2)
private Double salary;
@ExcelColumn(name = "入职时间", index = 5)
@ExcelDate(ColumnDateFormat.YYYY_MM_DD)
@ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
private Calendar startDate;
}Sheet Entity
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet
public class EmployeeSheet extends SheetData<EmployeeRow> {
public EmployeeSheet(String name) { super(name); }
}Generating Excel
@Resource
private GenerateExcel generateExcel;
@Test
public void testGenerateExcel() throws Exception {
List<EmployeeRow> employees = new ArrayList<>();
employees.add(new EmployeeRow(1, "宋江", "决策部", 87663D, Calendar.getInstance()));
employees.add(new EmployeeRow(2, "林冲", "战斗部", 45667D, Calendar.getInstance()));
employees.add(new EmployeeRow(3, "武松", "战斗部", 89766D, Calendar.getInstance()));
employees.add(new EmployeeRow(4, "潘金莲", "服务部", 123456D, Calendar.getInstance()));
EmployeeSheet sheet = new EmployeeSheet("Employees");
sheet.setRows(employees);
generateExcel.createFileXlsx(
new ReportExcel("公司员工信息", List.of(sheet)),
new FileOutputStream(new File("f:/emps.xlsx")));
}Core Generate APIs
createFileXls(ReportExcel)– Generates .xls (HSSF) as byte[]. createFileXls(ReportExcel, OutputStream) – Writes .xls to stream. createFileXlsx(ReportExcel) – Generates .xlsx (XSSF) as byte[]. createFileXlsx(ReportExcel, OutputStream) – Writes .xlsx to stream. createBigDataFileXlsx(ReportExcel) – Generates .xlsx using SXSSF (streaming) as byte[]. createBigDataFileXlsx(ReportExcel, OutputStream) – Writes SXSSF .xlsx to stream.
Generate CSV
generateCsv(CsvData<T>)– Generates CSV file as byte[].
JPA Query-Driven Export
Annotate the sheet class with a JPQL query:
@ExcelSheetLayout
@ExcelHeaderLayout
@ExcelMarginSheet(top = 1.5, bottom = 1.5, left = 1.5, right = 1.5)
@ExcelQuery("SELECT id, name, age, hire_date FROM employee WHERE dept = :dept ORDER BY dept_id")
public class EmployeeSheet extends QuerySheetData<EmployeeRow> {
public EmployeeSheet(String name) { super(name); }
}
// Usage
EmployeeSheet sheet = new EmployeeSheet("Employees");
sheet.addParameters("dept", "dev");
byte[] bytes = generateExcel.createFileXlsx(new ReportExcel("report", List.of(sheet)));Formula Calculation Columns
A column can be declared entirely via annotations without a corresponding field in the row entity. Formulas use ${fieldName} placeholders that resolve to actual Excel cell addresses at generation time.
@ExcelFunctionRows(excelFunctions = {
@ExcelFunctionRow(
excelColumn = @ExcelColumn(index = 9, name = "Taxation"),
excelCellsLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT, precision = 2),
excelFunction = @ExcelFunction(
function = "IF(${salary}<=28000,${salary}*0.23,IF(${salary}<=50000,${salary}*0.35,${salary}*0.43))",
nameFunction = "taxation"
)
)
})
public class EmployeeRow implements RowSheet {}The formula applies a progressive tax rate per row: salary ≤ 28,000 → 23%; 28,001–50,000 → 35%; > 50,000 → 43%. The nameFunction value ("taxation") uniquely identifies the computed column and can be referenced in @ExcelMergeRow or other formulas.
https://github.com/bld-commons/dev-excel
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary