Jxls2 图表模板的制作
源码:https://github.com/simter/simter-jxls-ext/commit/70fafca7bb3d43469a5200ca72e6e060dbdcbcfa
1. Excel 模板
jx:area(lastCell="C5")
jx:each(items="items" var="item" lastCell="C3")
${item.x}、${item.y1}、${item.y2}
$[SUM(B3)]、$[SUM(C3)]
java 代码:
// 模板文件
InputStream template = getClass().getClassLoader().getResourceAsStream("charts.xlsx");
// 输出文件
OutputStream output = new FileOutputStream("target/charts-result.xlsx");
// 数据
Context context = new Context();
List<Item> items = new ArrayList<>();
items.add(new Item("Derek", 3000, 2000));
...
context.putVar("items", items);
context.putVar("title", "X-Y");
context.putVar("ts", OffsetDateTime.now().toString());
// 渲染
// 注:必须设置 .setEvaluateFormulas(true),
// 否则生成的 Excel 文件,
// 在用到公式的地方不会显示公式的结果,
// 需要双击单元格回车才能看到公式结果。
JxlsHelper.getInstance().setEvaluateFormulas(true)
.processTemplate(template, output, context);
// Item 类
public Item(String x, int y1, int y2)
2. 渲染效果
3. 配置详解
3.1 使用名称管理器定义数据区域名称
XData引用位置=OFFSET(Sheet1!$A$2,1,0,COUNTA(Sheet1!$A:$A)-4,1)
Y1Data引用位置=OFFSET(Sheet1!XData,0,1)
Y2Data引用位置=OFFSET(Sheet1!XData,0,2)
充分利用 OFFSET 函数 基于“区域名称”定义图表XY轴的数据引用
3.2 配置图表的数据区引用上面定义好的数据区域名称
Y1系列值=Sheet1!Y1Data
Y2系列值=Sheet1!Y2Data
轴标签区域=Sheet1!XData