This project shows implementation a generic excel exporter developed in Java using Spring REST.
This service works with the HttpServletResponse, filename and the items.
@GetMapping("/export/products")
public void exportProductsToExcel(HttpServletResponse response) throws IOException, IllegalAccessException {
var products = dataService.findAllProduct();
ExcelExporterService excelExporterService = new ExcelExporterService();
excelExporterService.export(response, "Produtos", products);
}
This annotation is used for filter all class attributes that will be export.
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExportableField {
public String name() default "";
}
All attributes with @ExportableField annotation will be exportable, and value passed on name attribute will appear on Excel file, if doesn't setting, the default value shown will be the variable name.
public class Product {
@ExportableField(name = "Código")
private Long code;
@ExportableField(name = "Nome do produto")
private String description;
@ExportableField(name = "Preço")
private Double price = 0.0;
@ExportableField(name = "Categoria")
private Category category;
@ExportableField()
private Stock stock;
}
- Java 11
- Apache POI 5.0.0