温馨提示×

java中怎么用freemarker生成柱状图

小亿
90
2024-06-06 15:21:25
栏目: 编程语言

要在Java中使用Freemarker生成柱状图,首先需要准备好数据和模板文件。下面是一个简单的示例:

  1. 准备数据:
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. 准备模板文件(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();

以上代码将生成一个简单的包含数据的HTML文件,可以通过浏览器打开查看生成的柱状图。您可以根据自己的需求修改模板文件和数据,生成更复杂的柱状图。

0