Jxls2 圖表模板的制作
源碼:https://github.com/simter/simter-jxls-ext/commit/70fafca7bb3d43469a5200ca72e6e060dbdcbcfa
1. Excel 模板

jxls-01-template.png
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");
// 數(shù)據(jù)
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());
// 渲染
// 注:必須設(shè)置 .setEvaluateFormulas(true),
// 否則生成的 Excel 文件,
// 在用到公式的地方不會(huì)顯示公式的結(jié)果,
// 需要雙擊單元格回車才能看到公式結(jié)果。
JxlsHelper.getInstance().setEvaluateFormulas(true)
.processTemplate(template, output, context);
// Item 類
public Item(String x, int y1, int y2)
2. 渲染效果

jxls-02-out.png
3. 配置詳解
3.1 使用名稱管理器定義數(shù)據(jù)區(qū)域名稱

jxls-03-define-name.png
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 函數(shù) 基于“區(qū)域名稱”定義圖表XY軸的數(shù)據(jù)引用
3.2 配置圖表的數(shù)據(jù)區(qū)引用上面定義好的數(shù)據(jù)區(qū)域名稱

jxls-04-charts-config.png
Y1系列值=Sheet1!Y1Data
Y2系列值=Sheet1!Y2Data
軸標(biāo)簽區(qū)域=Sheet1!XData