java后臺生成統(tǒng)計圖+jfreechart、echarts

因業(yè)務(wù)需要生成報表,包含統(tǒng)計圖。

一、jfreechart ,這個是大眾最簡單的方式,只是圖片太丑了。(echarts的方法在下面)

jfreechart 的具體實現(xiàn),搭建個springboot的小工程即可

首先pom文件中引入jar包

        <!--用于jfreechart生成圖片  -->
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.5.0</version>
        </dependency>

實例代碼(有這一個就足夠了):

package com.example.poiword;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Rectangle;
import java.io.File;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

/**
 * @program: poi-word
 * @description:
 * @author: sunhui
 * @create: 2020-08-25 14:04
 **/
public class ChartUtils {
    private static String NO_DATA_MSG = "暫無數(shù)據(jù)";
    private static Font FONT = new Font("宋體", Font.PLAIN, 20);
    public static Color[] CHART_COLORS = {
            new Color(31,129,188), new Color(92,92,97), new Color(144,237,125), new Color(255,188,117),
            new Color(153,158,255), new Color(255,117,153), new Color(253,236,109), new Color(128,133,232),
            new Color(158,90,102),new Color(255, 204, 102) };// 顏色

    static{
        setChartTheme();
    }
    /**
     * 中文主題樣式 解決亂碼
     */
    public static void setChartTheme() {
        // 設(shè)置中文主題樣式 解決亂碼
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
        // 設(shè)置標(biāo)題字體
        chartTheme.setExtraLargeFont(FONT);
        // 設(shè)置圖例的字體
        chartTheme.setRegularFont(FONT);
        // 設(shè)置軸向的字體
        chartTheme.setLargeFont(FONT);
        chartTheme.setSmallFont(FONT);
        chartTheme.setTitlePaint(new Color(51, 51, 51));
        chartTheme.setSubtitlePaint(new Color(85, 85, 85));

        chartTheme.setLegendBackgroundPaint(Color.WHITE);// 設(shè)置標(biāo)注
        chartTheme.setLegendItemPaint(Color.BLACK);//
        chartTheme.setChartBackgroundPaint(Color.WHITE);
        // 繪制顏色繪制顏色.輪廓供應(yīng)商
        // paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence

        Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[] { Color.WHITE };
        // 繪制器顏色源
        DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS, OUTLINE_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
        chartTheme.setDrawingSupplier(drawingSupplier);

        chartTheme.setPlotBackgroundPaint(Color.WHITE);// 繪制區(qū)域
        chartTheme.setPlotOutlinePaint(Color.WHITE);// 繪制區(qū)域外邊框
        chartTheme.setLabelLinkPaint(new Color(8, 55, 114));// 鏈接標(biāo)簽顏色
        chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);

        chartTheme.setAxisOffset(new RectangleInsets(5, 12, 5, 12));
        chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));// X坐標(biāo)軸垂直網(wǎng)格顏色
        chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));// Y坐標(biāo)軸水平網(wǎng)格顏色

        chartTheme.setBaselinePaint(Color.WHITE);
        chartTheme.setCrosshairPaint(Color.BLUE);// 不確定含義
        chartTheme.setAxisLabelPaint(new Color(51, 51, 51));// 坐標(biāo)軸標(biāo)題文字顏色
        chartTheme.setTickLabelPaint(new Color(67, 67, 72));// 刻度數(shù)字
        chartTheme.setBarPainter(new StandardBarPainter());// 設(shè)置柱狀圖渲染
        chartTheme.setXYBarPainter(new StandardXYBarPainter());// XYBar 渲染

        chartTheme.setItemLabelPaint(Color.black);
        chartTheme.setThermometerPaint(Color.white);// 溫度計

        ChartFactory.setChartTheme(chartTheme);
    }

    public ChartUtils() {
    }


    /**
     * 必須設(shè)置文本抗鋸齒
     */
    public static void setAntiAlias(JFreeChart chart) {
        chart.setTextAntiAlias(false);

    }

    /**
     * 設(shè)置圖例無邊框,默認黑色邊框
     */
    public static void setLegendEmptyBorder(JFreeChart chart) {
        chart.getLegend().setFrame(new BlockBorder(Color.WHITE));

    }

    /**
     * 提供靜態(tài)方法:獲取報表圖形1:餅狀圖
     * @param title    標(biāo)題
     * @param datas    數(shù)據(jù)
     * @param url    字體
     */
    public static void createPiePort(String title, Map<String,Double> datas, String url){
        try {
            // 如果不使用Font,中文將顯示不出來
            DefaultPieDataset pds = new DefaultPieDataset();

            // 獲取迭代器:
            Set<Map.Entry<String, Double>> set =  datas.entrySet();
            Iterator iterator=(Iterator) set.iterator();
            Entry entry=null;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();
                pds.setValue(entry.getKey().toString(),Double.parseDouble(entry.getValue().toString()));
            }
            /**
             * 生成一個餅圖的圖表
             * 分別是:顯示圖表的標(biāo)題、需要提供對應(yīng)圖表的DateSet對象、是否顯示圖例、是否生成貼士以及是否生成URL鏈接
             */
            JFreeChart chart = ChartFactory.createPieChart(title, pds, true, true, true);
            setPieRender((PiePlot) chart.getPlot());

            //將內(nèi)存中的圖片寫到本地硬盤
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart,800,500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提供靜態(tài)方法:獲取報表圖形1:餅狀圖
     * @param title    標(biāo)題
     * @param datas    數(shù)據(jù)
     * @param url    字體
     */
    public static void createBarPort(String title, Map<String,Double> datas, String url){
        try {
            // 如果不使用Font,中文將顯示不出來
            DefaultCategoryDataset  pds = new DefaultCategoryDataset();

            // 獲取迭代器:
            Set<Map.Entry<String, Double>> set =  datas.entrySet();
            Iterator iterator=(Iterator) set.iterator();
            Entry entry=null;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();
                pds.setValue(Double.parseDouble(entry.getValue().toString()),entry.getKey().toString(),entry.getKey().toString());
            }
            /**
             * 生成一個餅圖的圖表
             * 分別是:顯示圖表的標(biāo)題、需要提供對應(yīng)圖表的DateSet對象、是否顯示圖例、是否生成貼士以及是否生成URL鏈接
             */
            JFreeChart chart = ChartFactory.createBarChart(title,"分類","數(shù)量", pds, PlotOrientation.VERTICAL, true, true, false);

            //將內(nèi)存中的圖片寫到本地硬盤
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart,800,500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 提供靜態(tài)方法:獲取報表圖形3:折線圖
     * @param title        標(biāo)題
     * @param datas        數(shù)據(jù)
     * @param xName        分類(第一季,第二季.....)
     * @param yName    柱狀圖的數(shù)量單位
     * @param url        字體
     */
    public static void createLinePort(String title,Map<String,Double> datas,String xName,String yName,String url){
        try {
            //種類數(shù)據(jù)集
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            //獲取迭代器:
            Set<Entry<String, Double>> set =  datas.entrySet();
            Iterator iterator=(Iterator) set.iterator();
            Entry entry=null;
            while(iterator.hasNext()){
                entry=(Entry) iterator.next();
                dataset.setValue(Double.parseDouble(entry.getValue().toString()),//y
                        title,                         //名稱
                        entry.getKey().toString());      //x
            }
            //創(chuàng)建折線圖,折線圖分水平顯示和垂直顯示兩種
            JFreeChart chart = ChartFactory.createLineChart(title, xName, yName, dataset,//2D折線圖
                    PlotOrientation.VERTICAL,
                    false, // 是否顯示圖例(對于簡單的柱狀圖必須是false)
                    true, // 是否生成工具
                    true);// 是否生成URL鏈接
            //得到繪圖區(qū)
            setLineRender((CategoryPlot)chart.getPlot(),true,true);
            org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 1000,600);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 設(shè)置折線圖樣式
     *
     * @param plot
     * @param isShowDataLabels
     *            是否顯示數(shù)據(jù)標(biāo)簽
     */
    public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels, boolean isShapesVisible) {
        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 0, 10), false);
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setDefaultStroke(new BasicStroke(1.5F));
        if (isShowDataLabels) {
            renderer.setDefaultItemLabelsVisible(true);
            renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
                    NumberFormat.getInstance()));
            renderer.setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));// weizhi
        }
        renderer.setDefaultShapesVisible(isShapesVisible);// 數(shù)據(jù)點繪制形狀
        setXAixs(plot);
        setYAixs(plot);

    }
    /**
     * 設(shè)置餅狀圖渲染
     */
    public static void setBarRender(Plot plot) {

//        CategoryAxis categoryAxis=plot.getDomainAxis();//獲得橫坐標(biāo)
//        categoryAxis.setLabelFont(new Font("微軟雅黑",Font.BOLD,12));//設(shè)置橫坐標(biāo)字體
    }
    /**
     * 設(shè)置餅狀圖渲染
     */
    public static void setPieRender(Plot plot) {

        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 5, 10));
        PiePlot piePlot = (PiePlot) plot;
        piePlot.setInsets(new RectangleInsets(0, 0, 0, 0));
        piePlot.setCircular(true);// 圓形

        // piePlot.setSimpleLabels(true);// 簡單標(biāo)簽
        piePlot.setLabelGap(0.01);
        piePlot.setInteriorGap(0.05D);
        piePlot.setLegendItemShape(new Rectangle(10, 10));// 圖例形狀
        piePlot.setIgnoreNullValues(true);
        piePlot.setLabelBackgroundPaint(null);// 去掉背景色
        piePlot.setLabelShadowPaint(null);// 去掉陰影
        piePlot.setLabelOutlinePaint(null);// 去掉邊框
        piePlot.setShadowPaint(null);
        // 0:category 1:value:2 :percentage
        piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{2}"));// 顯示標(biāo)簽數(shù)據(jù)
    }

    /**
     * 設(shè)置類別圖表(CategoryPlot) X坐標(biāo)軸線條顏色和樣式
     *
     * @param plot
     */
    public static void setXAixs(CategoryPlot plot) {
        Color lineColor = new Color(31, 121, 170);
        plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
        plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐標(biāo)軸顏色
        plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐標(biāo)軸標(biāo)記|豎線顏色

    }

    /**
     * 設(shè)置類別圖表(CategoryPlot) Y坐標(biāo)軸線條顏色和樣式 同時防止數(shù)據(jù)無法顯示
     *
     * @param plot
     */
    public static void setYAixs(CategoryPlot plot) {
//      Color lineColor = new Color(192, 208, 224);
        Color lineColor = new Color(31, 121, 170);
        ValueAxis axis = plot.getRangeAxis();
        axis.setAxisLinePaint(lineColor);// Y坐標(biāo)軸顏色
        axis.setTickMarkPaint(lineColor);// Y坐標(biāo)軸標(biāo)記|豎線顏色
        // false隱藏Y刻度
        axis.setAxisLineVisible(true);
        axis.setTickMarksVisible(true);
        // Y軸網(wǎng)格線條
        plot.setRangeGridlinePaint(new Color(192, 192, 192));
        plot.setRangeGridlineStroke(new BasicStroke(1));

        plot.getRangeAxis().setUpperMargin(0.1);// 設(shè)置頂部Y坐標(biāo)軸間距,防止數(shù)據(jù)無法顯示
        plot.getRangeAxis().setLowerMargin(0.1);// 設(shè)置底部Y坐標(biāo)軸間距

    }

    /**
     * 設(shè)置XY圖表(XYPlot) X坐標(biāo)軸線條顏色和樣式
     *
     * @param plot
     */
    public static void setXY_XAixs(XYPlot plot) {
        Color lineColor = new Color(31, 121, 170);
        plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐標(biāo)軸顏色
        plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐標(biāo)軸標(biāo)記|豎線顏色

    }

    /**
     * 設(shè)置XY圖表(XYPlot) Y坐標(biāo)軸線條顏色和樣式 同時防止數(shù)據(jù)無法顯示
     *
     * @param plot
     */
    public static void setXY_YAixs(XYPlot plot) {
        Color lineColor = new Color(192, 208, 224);
        ValueAxis axis = plot.getRangeAxis();
        axis.setAxisLinePaint(lineColor);// X坐標(biāo)軸顏色
        axis.setTickMarkPaint(lineColor);// X坐標(biāo)軸標(biāo)記|豎線顏色
        // 隱藏Y刻度
        axis.setAxisLineVisible(false);
        axis.setTickMarksVisible(false);
        // Y軸網(wǎng)格線條
        plot.setRangeGridlinePaint(new Color(192, 192, 192));
        plot.setRangeGridlineStroke(new BasicStroke(1));
        plot.setDomainGridlinesVisible(false);

        plot.getRangeAxis().setUpperMargin(0.12);// 設(shè)置頂部Y坐標(biāo)軸間距,防止數(shù)據(jù)無法顯示
        plot.getRangeAxis().setLowerMargin(0.12);// 設(shè)置底部Y坐標(biāo)軸間距

    }

    public static void main(String[] args) {
        Map<String, Double> map=new HashMap<String, Double>();
        map.put("冠心病", (double) 1000);
        map.put("腦卒中", (double) 700);
        map.put("肺結(jié)核", (double) 600);
        map.put("糖尿病", (double) 400);
        map.put("高血壓", (double) 100);
        map.put("精神病", (double) 2000);
        createPiePort("慢病統(tǒng)計結(jié)果", map,"E:\\data\\aa.jpg");

        Map<String, Double> map1=new HashMap<String, Double>();
        //設(shè)置第一期的投票信息
        map1.put("2020-02-03", (double) 700);
        map1.put("2020-02-04", (double) 1000);
        map1.put("2020-02-05", (double) 600);
        map1.put("2020-02-06", (double) 400);
        map1.put("2020-02-07", (double) 4000);
        map1.put("2020-02-08", (double) 1200);
        map1.put("2020-02-09", (double) 800);
        createLinePort("近7日金額(日報)",map1,"日期","金額(元)","E:\\data\\bb.jpg");

        Map<String, Double> map2=new HashMap<String, Double>();
        map2.put("冠心病", (double) 1000);
        map2.put("腦卒中", (double) 700);
        map2.put("肺結(jié)核", (double) 600);
        map2.put("糖尿病", (double) 400);
        map2.put("高血壓", (double) 100);
        map2.put("精神病", (double) 2000);
        createBarPort("慢病統(tǒng)計結(jié)果", map2,"E:\\data\\cc.jpg");
    }

}

二、echarts,這個需要依賴一些小工具phantomjs、echarts-convert

phantomjs下載地址:https://phantomjs.org/download.html
echarts-convert下載地址:https://gitee.com/saintlee/echartsconvert

首先按照phantomjs文檔配置環(huán)境變量,其次啟動服務(wù):

phantomjs echarts-convert.js的路徑 -s -p 端口號
windows下實例:phantomjs echarts-convert.js -s -p 6666
其他雷同

這個地方注意下,很多文檔直接帶入?yún)?shù)或者json之類的來指定輸入輸出文件地址來生成,個人測試只有這種方式能夠生成:phantomjs echarts-convert.js的路徑 -infile 數(shù)據(jù)文件路徑 -outfile 輸出的文件路徑

另一個注意事項,echarts-convert下載后,不需要改動文件,不需要用jquery,什么都不要動。

下面就可以愉快的開始了:

說明:本文直接通過freemarker遠程訪問剛才的啟動的服務(wù)端口來生成的圖片
以下內(nèi)容轉(zhuǎn)載地址: http://www.itdecent.cn/p/dfc28fd7d786
和原文有非常小的區(qū)別,比如文件存放路徑之類的。

1、pom.xml文件:

        <!--phantomjs服務(wù)端模式-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.7</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

2、EchartsUtil.java 工具類

package com.example.poiword.phantomjs;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class EchartsUtil {
    private static String url = "http://localhost:6666";
    private static final String SUCCESS_CODE = "1";

    public static String generateEchartsBase64(String option) throws ClientProtocolException, IOException {
        String base64 = "";
        if (option == null) {
            return base64;
        }
        option = option.replaceAll("\\s+", "").replaceAll("\"", "'");

        // 將option字符串作為參數(shù)發(fā)送給echartsConvert服務(wù)器
        Map<String, String> params = new HashMap<>();
        params.put("opt", option);
        String response = HttpUtil.post(url, params, "utf-8");

        // 解析echartsConvert響應(yīng)
        JSONObject responseJson = JSON.parseObject(response);
        String code = responseJson.getString("code");

        // 如果echartsConvert正常返回
        if (SUCCESS_CODE.equals(code)) {
            base64 = responseJson.getString("data");
        }
        // 未正常返回
        else {
            String string = responseJson.getString("msg");
            throw new RuntimeException(string);
        }

        return base64;
    }
}

3、FreemarkerUtil.java

package com.example.poiword.phantomjs;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {
    private static final String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();

    public static String generateString(String templateFileName, String templateDirectory, Map<String, Object> datas)
            throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);

        // 設(shè)置默認編碼
        configuration.setDefaultEncoding("UTF-8");

        // 設(shè)置模板所在文件夾
        configuration.setDirectoryForTemplateLoading(new File(path + templateDirectory));

        // 生成模板對象
        Template template = configuration.getTemplate(templateFileName);

        // 將datas寫入模板并返回
        try (StringWriter stringWriter = new StringWriter()) {
            template.process(datas, stringWriter);
            stringWriter.flush();
            return stringWriter.getBuffer().toString();
        }
    }
}

4、HttpUtil.java

package com.example.poiword.phantomjs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    public static String post(String url, Map<String, String> params, String charset)
            throws ClientProtocolException, IOException {
        String responseEntity = "";

        // 創(chuàng)建CloseableHttpClient對象
        CloseableHttpClient client = HttpClients.createDefault();

        // 創(chuàng)建post方式請求對象
        HttpPost httpPost = new HttpPost(url);

        // 生成請求參數(shù)
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        // 將參數(shù)添加到post請求中
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));

        // 發(fā)送請求,獲取結(jié)果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);

        // 獲取響應(yīng)實體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 按指定編碼轉(zhuǎn)換結(jié)果實體為String類型
            responseEntity = EntityUtils.toString(entity, charset);
        }

        // 釋放資源
        EntityUtils.consume(entity);
        response.close();

        return responseEntity;
    }
}

5、option.ftl 這里可以根據(jù)官方文檔來配置不同的圖表

{
    title: {
        text:'${title}',
        x:'middle',
        textAlign:'center'
    },
    xAxis: {
        type: 'category',
        data: ${categories}
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: ${values},
        type: 'pie'
    }]
}

6、App.java

package com.example.poiword.phantomjs;

import com.alibaba.fastjson.JSON;
import freemarker.template.TemplateException;
import org.apache.http.client.ClientProtocolException;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @program: poi-word
 * @description:
 * @author: sunhui
 * @create: 2020-08-26 11:24
 **/
public class App {
    public static void main(String[] args) throws ClientProtocolException, IOException, TemplateException {
        // 變量
        String title = "水果";
        String[] categories = new String[] { "蘋果", "香蕉", "西瓜" };
        int[] values = new int[] { 3, 2, 1 };

        // 模板參數(shù)
        HashMap<String, Object> datas = new HashMap<>();
        datas.put("categories", JSON.toJSONString(categories));
        datas.put("values", JSON.toJSONString(values));
        datas.put("title", title);

        // 生成option字符串
        String option = FreemarkerUtil.generateString("option.ftl", "/templates", datas);

        // 根據(jù)option參數(shù)
        String base64 = EchartsUtil.generateEchartsBase64(option);

        System.out.println("BASE64:" + base64);
        generateImage(base64, "E:\\echarts-back\\new1\\test-pie.png");
    }

    public static void generateImage(String base64, String path) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        try (OutputStream out = new FileOutputStream(path)){
            // 解密
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容