Generate Word Reports with YARG in Spring Boot 3.2.5 – A Step-by-Step Guide
This tutorial demonstrates how to use the open‑source YARG library with Spring Boot 3.2.5 to create Word (.docx) reports by preparing a template, loading it, supplying JSON data, defining a data band, and running the report generation code, complete with Maven dependencies and example screenshots.
1. Introduction
Yet Another Report Generator (YARG) is an open‑source Java reporting library that can create documents in formats such as .docx, .xls, .html, .csv, etc., by filling templates with data loaded from SQL, Groovy or JSON. This article shows how to use a Spring Boot 3.2.5 @RestController to generate a .docx file from JSON data.
2. Practical Example
2.1 Add Maven Dependency
<code><dependency>
<groupId>com.haulmont.yarg</groupId>
<artifactId>yarg</artifactId>
<version>2.2.14</version>
</dependency>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>repo-cuba-platform-work</id>
<name>repo</name>
<url>https://repo.cuba-platform.com/content/groups/work</url>
</repository>
</repositories>
</code>2.2 Design Word Template
2.3 Load Template
<code>ReportBuilder reportBuilder = new ReportBuilder();
ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder()
.documentPath(new ClassPathResource("templates/day.docx").getURI().getPath())
.documentName("day.docx")
.outputType(ReportOutputType.docx)
.readFileFromPath();
reportBuilder.template(reportTemplateBuilder.build());
</code>2.4 Prepare Data
<code>Map<String, Object> data = Map.of(
"date", "2018-12-20", "p1", 234, "p2", 123,
"p3", 489, "p4", 789, "p5", 127, "p6", 489);
String jsonStr = new ObjectMapper().writeValueAsString(data);
</code>2.5 Define Data Band
<code>BandBuilder bandBuilder = new BandBuilder();
ReportBand r = bandBuilder.name("R")
.query("R", "parameter=p$", "json")
.build();
reportBuilder.band(r);
</code>2.6 Generate Report
<code>Report report = reportBuilder.build();
Reporting reporting = new Reporting();
reporting.setFormatterFactory(new DefaultFormatterFactory());
reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader()));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
reporting.runReport(new RunParams(report).param("p", jsonStr), response.getOutputStream());
</code>The above steps produce a downloadable Word file containing the filled data, as shown in the following screenshots.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.