溫馨提示×

java中怎么用freemarker生成柱狀圖

小億
110
2024-06-06 15:21:25
欄目: 編程語言

要在Java中使用Freemarker生成柱狀圖,首先需要準(zhǔn)備好數(shù)據(jù)和模板文件。下面是一個(gè)簡單的示例:

  1. 準(zhǔn)備數(shù)據(jù):
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> item1 = new HashMap<>();
item1.put("label", "A");
item1.put("value", 10);
data.add(item1);

Map<String, Object> item2 = new HashMap<>();
item2.put("label", "B");
item2.put("value", 20);
data.add(item2);

Map<String, Object> item3 = new HashMap<>();
item3.put("label", "C");
item3.put("value", 30);
data.add(item3);
  1. 準(zhǔn)備模板文件(bar_chart.ftl):
<html>
<head>
    <title>Bar Chart</title>
</head>
<body>
    <h1>Bar Chart</h1>
    <table border="1">
        <tr>
            <th>Label</th>
            <th>Value</th>
        </tr>
        <#list data as item>
            <tr>
                <td>${item.label}</td>
                <td>${item.value}</td>
            </tr>
        </#list>
    </table>
</body>
</html>
  1. 使用Freemarker生成HTML文件:
Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
cfg.setClassForTemplateLoading(ChartGenerator.class, "/");
Template template = cfg.getTemplate("bar_chart.ftl");

Map<String, Object> root = new HashMap<>();
root.put("data", data);

Writer out = new OutputStreamWriter(new FileOutputStream("bar_chart.html"));
template.process(root, out);
out.flush();
out.close();

以上代碼將生成一個(gè)簡單的包含數(shù)據(jù)的HTML文件,可以通過瀏覽器打開查看生成的柱狀圖。您可以根據(jù)自己的需求修改模板文件和數(shù)據(jù),生成更復(fù)雜的柱狀圖。

0