Using JXLS for Complex Excel Export in Java Backend Applications
This article introduces the JXLS library for Java, explains how to add Maven dependencies, provides backend utility and controller code for exporting Excel files, and details common XLS expressions such as jx:area, jx:each, jx:mergeCells, and dynamic column handling to simplify complex Excel report generation.
When simple Excel exports can be handled by POI or EasyExcel, complex requirements—fixed styles, merged cells, dynamic columns—often demand more effort; JXLS, a lightweight Java library, addresses these challenges.
JXLS official site: https://jxls.sourceforge.net/
Adding Maven Dependencies
<!-- Version may vary; using 2.11.0 as example -->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>2.11.0</version>
</dependency>
<!-- For JavaExcelAPI‑based converter -->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>${jxlsJexcelVersion}</version>
</dependency>Backend Utility Class
public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
Context context = new Context();
if (model != null) {
for (String key : model.keySet()) {
context.putVar(key, model.get(key));
}
}
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(is, os);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<>();
funcs.put("utils", new JxlsUtils()); // add custom functions
evaluator.setJexlEngine(new JexlBuilder().namespaces(funcs).create());
jxlsHelper.processTemplate(context, transformer);
}Export Controller
// Example controller method
@PostMapping("/export/exportTradeCreditData")
@ResponseBody
public void exportTradeCreditData(HttpServletRequest request, HttpServletResponse response, Date countDate) {
String templatePath = "template/excel/trade_credit_data.xlsx";
URL templateResource = PathTools.findResource(templatePath);
try (OutputStream out = response.getOutputStream();
InputStream templateStream = templateResource.openStream()) {
List<CindaTradeCreditDto> list = countingReportService.queryTradeCreditData(countDate);
Map<String, Object> map = new HashMap<>();
map.put("year", getYear(countDate));
map.put("contracts", list);
JxlsUtils.exportExcel(templateStream, out, map);
out.close();
} catch (Exception e) {
e.printStackTrace();
log.error("导出excel异常, {}", JxlsUtils.executeException(e));
}
}Creating the Excel Template
Use an .xlsx workbook (not .xls ) and design the sheet layout according to export requirements; only simple header/row styling, column/row sizes, and cell merging are supported. Insert JXLS expressions as cell comments (Shift+F2 in Office).
XLS Expressions
jx:area
jx:area(lastCell = "H3")The jx:area command defines the rectangular region (from A1 to the specified last cell) that JXLS will parse, improving processing speed.
jx:each (most common)
jx:each(items="contracts" var="contract" lastCell="H3")items : name of the collection in the context.
var : variable name for each element during iteration.
area : the parsing region for this command.
direction : fill direction, default DOWN .
select : optional filter expression.
For horizontal (dynamic column) iteration, set direction="RIGHT" :
jx:each(items="countMonths" var="month" lastCell="C3" direction="RIGHT")jx:mergeCells
jx:mergeCells(lastCell="合并单元格范围" [, cols="合并的列数"] [, rows="合并的行数"] [, minCols="要合并的最小列数"] [, minRows="要合并的最小行数"])This command merges cells only if they have not been merged previously.
Dynamic Columns – Combined Usage
jx:each(items="countMonths" var="month" lastCell="C3" direction="RIGHT")In the template, use expressions such as ${empty(colData.monthData.get(month)) ? 0 : colData.monthData.get(month)} to safely output values for each dynamic column.
Summary
The above snippets demonstrate the most frequently used JXLS operations for exporting complex Excel reports, including Maven setup, backend utility methods, controller integration, template preparation, and key XLS expressions for areas, loops, cell merging, and dynamic columns.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.