国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Java生成Echarts表圖的兩種方案

這篇具有很好參考價(jià)值的文章主要介紹了Java生成Echarts表圖的兩種方案。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

最近被生成報(bào)告糾結(jié)了一個(gè)禮拜,生成word并不難,可以通過(guò)模版來(lái)實(shí)現(xiàn),目前用得比較多的技術(shù)有,poi,freemarker等等工具,只需要自己寫(xiě)一個(gè)模版通過(guò)占位符的形式來(lái)替換里面的變量。這里生成word就不過(guò)多去介紹(后期出一篇文章)但是里面的圖表就沒(méi)有那么好去實(shí)現(xiàn),要考慮到通過(guò)后臺(tái)獲取數(shù)據(jù)來(lái)生成圖表。經(jīng)過(guò)了一個(gè)禮拜的查閱資料找到了兩種在后端實(shí)現(xiàn)方式,本篇以生成柱狀圖為例:

一 Jfreechart

  1. 簡(jiǎn)介
    JFreeChart是JAVA平臺(tái)上的一個(gè)開(kāi)放的圖表繪制類(lèi)庫(kù)。它完全使用JAVA語(yǔ)言編寫(xiě),是為applications, applets, servlets 以及JSP等使用所設(shè)計(jì)。JFreeChart可生成餅圖(pie charts)、柱狀圖(bar charts)、散點(diǎn)圖(scatter plots)、時(shí)序圖(time series)、甘特圖(Gantt charts)等等多種圖表,并且可以產(chǎn)生PNG和JPEG格式的輸出,還可以與PDF和EXCEL關(guān)聯(lián)。
  2. 導(dǎo)入依賴(lài)
		 <dependency>
            <groupId>jfreechart</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.0</version>
        </dependency>
  1. 簡(jiǎn)單demo
 /**
     * 功能描述: 創(chuàng)建JFreeChart對(duì)象并設(shè)置樣式
     *
     * @param categoryDataset 類(lèi)別數(shù)據(jù)集
     * @return org.jfree.chart.JFreeChart
     * @author Jack_Liberty
     * @date 2021-04-01 11:16
     */
    public static JFreeChart createChart(CategoryDataset categoryDataset) {
        JFreeChart jfreechart = ChartFactory.createBarChart("Test", "", "", categoryDataset,
                PlotOrientation.VERTICAL, false, false, false);

        Font labelFont = new Font(Font.SANS_SERIF, Font.TRUETYPE_FONT, 15);
//        Font labelFont1 = new Font(Font.SANS_SERIF, Font.TRUETYPE_FONT, 24);

//         jfreechart.setTextAntiAlias(false);
        jfreechart.setBackgroundPaint(Color.white);
        // 獲得圖表區(qū)域?qū)ο?/span>
        CategoryPlot plot = jfreechart.getCategoryPlot();

        // 設(shè)置橫虛線(xiàn)可見(jiàn)
        plot.setRangeGridlinesVisible(true);
        // 虛線(xiàn)色彩
        plot.setRangeGridlinePaint(Color.gray);
        // 數(shù)據(jù)軸精度
        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        DecimalFormat df = new DecimalFormat("#0.0");
        // 數(shù)據(jù)軸數(shù)據(jù)標(biāo)簽的顯示格式
        vn.setNumberFormatOverride(df);

        // x軸設(shè)置
        CategoryAxis domainAxis = plot.getDomainAxis();
        // 軸標(biāo)題
        domainAxis.setLabelFont(labelFont);
        // 軸數(shù)值
        domainAxis.setTickLabelFont(labelFont);
        // X軸標(biāo)題過(guò)長(zhǎng)可設(shè)置傾斜度
          domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 3.0));
        // 橫軸上的 Label
        domainAxis.setMaximumCategoryLabelWidthRatio(6.00f);
        // 是否完整顯示

        // 設(shè)置距離圖片左端距離
        domainAxis.setLowerMargin(0.0);
        // 設(shè)置距離圖片右端距離
        domainAxis.setUpperMargin(0.0);
        // 設(shè)置 columnKey 是否間隔顯示
        plot.setDomainAxis(domainAxis);
        // 設(shè)置柱圖背景色(注意,系統(tǒng)取色的時(shí)候要使用16位的模式來(lái)查看顏色編碼,這樣比較準(zhǔn)確)
        plot.setBackgroundPaint(new Color(255, 255, 255, 255));

        // y軸設(shè)置
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setLabelFont(labelFont);
        rangeAxis.setTickLabelFont(labelFont);
        // 設(shè)置最高的一個(gè) Item 與圖片頂端的距離
        rangeAxis.setUpperMargin(0.15);
        // 設(shè)置最低的一個(gè) Item 與圖片底端的距離
        rangeAxis.setLowerMargin(0.15);
        plot.setRangeAxis(rangeAxis);

        // 解決中文亂碼問(wèn)題(關(guān)鍵)
        TextTitle textTitle = jfreechart.getTitle();
        textTitle.setFont(new Font("黑體", Font.PLAIN, 20));
        domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 15));
        domainAxis.setLabelFont(new Font("宋體", Font.PLAIN, 15));
        vn.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 15));
        vn.setLabelFont(new Font("黑體", Font.PLAIN, 15));


        // 使用自定義的渲染器
        CustomRenderer renderer = new CustomRenderer();
        ArrayList<Double> data = new ArrayList<Double>();
        data.add(99D);
        data.add(87D);
        data.add(89D);
        data.add(45D);
        data.add(78D);
        data.add(92D);
        data.add(98D);
        data.add(80D);
        renderer.setScores(data);
        // 設(shè)置柱子寬度
        renderer.setMaximumBarWidth(0.1);
        // 設(shè)置柱子高度
        renderer.setMinimumBarLength(0.1);
        // 設(shè)置柱子邊框顏色
        renderer.setBaseOutlinePaint(Color.BLACK);
        // 設(shè)置柱子邊框可見(jiàn)
        renderer.setDrawBarOutline(true);
        // 設(shè)置每個(gè)地區(qū)所包含的平行柱的之間距離
        renderer.setItemMargin(1);
        jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

        // 顯示每個(gè)柱的數(shù)值,并修改該數(shù)值的字體屬性
//          renderer.setIncludeBaseInRange(true);

        renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        plot.setRenderer(renderer);
        // 設(shè)置柱的透明度
        plot.setForegroundAlpha(1.0f);
        // 背景色 透明度
        plot.setBackgroundAlpha(0.5f);
        return jfreechart;
    }
   /**
     * 功能描述: 創(chuàng)建CategoryDataset對(duì)象
     *
     * @return org.jfree.data.category.CategoryDataset
     * @author Jack_Liberty
     * @date 2021-04-01 16:20
     */
    public static CategoryDataset createDataset() {
         double[][] data = new double[][]{{1,9,0,15,9,3,4}};
        String[] rowKeys = {"1"};
        String[] columnKeys = {"Test1","Test2","Test3","Test4","Test5","Test6","Test7"};
        return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);
    }
  1. 啟動(dòng)測(cè)試
    public static void main(String[] args) throws Exception {
        // 創(chuàng)建CategoryDataset對(duì)象
        CategoryDataset dataset = createDataset();
        // 根據(jù)Dataset 生成JFreeChart對(duì)象,并設(shè)置相應(yīng)的樣式
        JFreeChart freeChart = createChart(dataset);

        FileOutputStream out = null;
        try {
            out = new FileOutputStream("F:\\chart110605.png");
            ChartUtilities.writeChartAsPNG(out, freeChart,
                    800, 450);// 輸出圖表
            System.out.println("圖片運(yùn)行成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (final Exception ex) {
                ex.printStackTrace();
            }
        }

    }
  1. 生成圖片展示
    java生成echarts圖表,java,echarts,開(kāi)發(fā)語(yǔ)言
    第一種方式到此為止,下面上第二種

Echarts插件

  1. 簡(jiǎn)介
    Echarts在熟悉了解前端的一定不會(huì)感到陌生,ECharts是一款基于JavaScript的數(shù)據(jù)可視化圖表庫(kù),提供直觀(guān),生動(dòng),可交互,可個(gè)性化定制的數(shù)據(jù)可視化圖表。ECharts最初由百度團(tuán)隊(duì)開(kāi)源,并于2018年初捐贈(zèng)給Apache基金會(huì),成為ASF孵化級(jí)項(xiàng)目。
    Echarts官網(wǎng)鏈接: https://echarts.apache.org/zh/index.html

Echarts插件安裝包
鏈接:https://pan.baidu.com/s/19399TOP_2i3GM-wR3Q71XA
提取碼:kl66
解壓后里面包含phantomjs-2.1.1-windows和echarts-convert.js,進(jìn)入\echarts\phantomjs-2.1.1-windows\bin目錄下通過(guò)cmd命令啟動(dòng)phantomjs D:\toos\echarts\saintlee-echartsconvert-master\echartsconvert\echarts-convert.js -s -p 6666

  1. 導(dǎo)入依賴(lài)
		 <dependency>
            <groupId>com.github.abel533</groupId>
            <artifactId>Echarts</artifactId>
            <version>3.0.0.6</version>
        </dependency>

  1. 直接上代碼
    這里是echarts-pojo模塊(數(shù)據(jù)模型)
/**
 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 14:11
 **/
@Data
public class BarParam {
    private Object[] barName;

    private Object[] barValue;

    private String legendName;
}
/**
 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 14:11
 **/
@Data
public class BarData {

    private String title;  //標(biāo)題

    private BarParam barParamList;

    private Boolean isHorizontal;  //是否水平放置

    //省略get/set方法,使用lombok插件@Data

}

對(duì)GsonOption.java做一層封裝,繼承GsonOption 類(lèi)

 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 14:13
 **/
@Data
public class EnhancedOption extends GsonOption {
    private String filepath;

    private static boolean VIEW =false;
    private static String EXPORT_PATH  ="";


    /**
     * 輸出到控制臺(tái)
     */
    public void print() {
        GsonUtil.print(this);
    }

    /**
     * 輸出到控制臺(tái)
     */
    public void printPretty() {
        GsonUtil.printPretty(this);
    }

    /**
     * 在瀏覽器中查看
     */
    public void view() {
        if (!VIEW) {
            return;
        }
        if (this.filepath != null) {
            try {
                OptionUtil.browse(this.filepath);
            } catch (Exception e) {
                this.filepath = OptionUtil.browse(this);
            }
        } else {
            this.filepath = OptionUtil.browse(this);
        }
    }

    /**
     * 導(dǎo)出到指定文件名
     *
     * @param fileName
     * @return 返回html路徑
     */
    public String exportToHtml(String fileName) {
        return exportToHtml(EXPORT_PATH, fileName);
    }
}

請(qǐng)求工具類(lèi)

/**
 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 14:02
 **/
@Slf4j
public class HttpUtil {


    /**
     * 發(fā)送post請(qǐng)求
     * @param url
     * @param params
     * @param charset
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params, String charset)
            throws ClientProtocolException, IOException {
        log.info("httpPostRequest url : " + url + "   paramMap : " + params);
        String responseEntity = "";

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

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

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

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

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

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

        // 釋放資源
        EntityUtils.consume(entity);
        response.close();
        //System.out.println("responseEntity = " + responseEntity);

        return responseEntity;
    }

    public static String postUrl(String url, Map<String, Object> params, String charset) {
        String responseEntity = "";
        // 創(chuàng)建CloseableHttpClient對(duì)象
        CloseableHttpClient client = HttpClients.createDefault();
        // 創(chuàng)建post方式請(qǐng)求對(duì)象
        HttpPost httpPost = new HttpPost(url);
        // 將參數(shù)添加到post請(qǐng)求中
        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(params), charset));
        // 發(fā)送請(qǐng)求,獲取結(jié)果(同步阻塞)
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            // 獲取響應(yīng)實(shí)體
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 按指定編碼轉(zhuǎn)換結(jié)果實(shí)體為String類(lèi)型
                responseEntity = EntityUtils.toString(entity, charset);
            }
            // 釋放資源
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    /**
     * post請(qǐng)求(用于請(qǐng)求json格式的參數(shù))
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception {

        log.info("httpPostRequest url : " + url + "   paramMap : " + params);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 創(chuàng)建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        //logger.info("entity = " + entity);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            //logger.info("response = " + response);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                log.info("post請(qǐng)求響應(yīng)結(jié)果:{}", jsonString);
                return jsonString;
            }
            else{
                log.error("請(qǐng)求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }

    /**
     * http發(fā)送POST請(qǐng)求
     *
     * @author J.M.C
     * @since 2019年1月16日
     * @param url 長(zhǎng)連接URL
     * @param paramsJson 請(qǐng)求參數(shù)body
     * @return result 字符串
     */
    public static String doPostJson(String url, JSONObject paramsJson) {
        log.info("httpPostRequest url : " + url + "   paramMap : " + paramsJson);
        if(StringUtils.isBlank(url)){
            log.error("httpPostRequest url is null");
            return null;
        }
        String result = "";
        try {
            // 創(chuàng)建httpClient實(shí)例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 創(chuàng)建httpPost遠(yuǎn)程連接實(shí)例
            HttpPost httpPost = new HttpPost(url);
            // 配置請(qǐng)求參數(shù)實(shí)例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 設(shè)置連接主機(jī)服務(wù)超時(shí)時(shí)間
                    .setConnectionRequestTimeout(10000)// 設(shè)置連接請(qǐng)求超時(shí)時(shí)間
                    .setSocketTimeout(30000)// 設(shè)置讀取數(shù)據(jù)連接超時(shí)時(shí)間
                    .build();
            // 為httpPost實(shí)例設(shè)置配置
            httpPost.setConfig(requestConfig);
            // 設(shè)置請(qǐng)求頭
            httpPost.addHeader("content-type", "application/json;charset=utf-8");
            // 封裝post請(qǐng)求參數(shù)
            httpPost.setEntity(new StringEntity(paramsJson.toJSONString(), Charset.forName("UTF-8")));
            // httpClient對(duì)象執(zhí)行post請(qǐng)求,并返回響應(yīng)參數(shù)對(duì)象
            //   HttpResponse httpResponse = httpClient.execute(httpPost);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            // 從響應(yīng)對(duì)象中獲取響應(yīng)內(nèi)容
            result = EntityUtils.toString(httpResponse.getEntity());
            //logger.info("result = {}" , result);
        } catch (UnsupportedEncodingException e) {
            log.error("URLUtil.httpPostRequest encounters an UnsupportedEncodingException : {}",e);
        } catch (IOException e) {
            log.error("URLUtil.httpPostRequest encounters an IOException : {}",e);
        }
        log.info("URLUtil.httpPostRequest -----result----: " + result);
        return result;
    }
}
**文件工具類(lèi)**

/**
 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 15:31
 **/
public class FileUtil {
    public static File generateImage(String base64, String path) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        File file = new File(path);
        String fileName = file.getName();
        System.out.println("file = " + file);
        //創(chuàng)建臨時(shí)文件
        //File tempFile = File.createTempFile(fileName, ".png");
        //FileOutputStream fos = new FileOutputStream(tempFile);*/

        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();
            return file;
        }
       /* finally {
            //關(guān)閉臨時(shí)文件
            fos.flush();
            fos.close();
            try {
                Thread.sleep(10000);
                tempFile.deleteOnExit();//程序退出時(shí)刪除臨時(shí)文件
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        */

    }

    public static void deleteFile(File file) {
        //File file = new File();
        String fileName = file.getName();
        // 如果文件路徑所對(duì)應(yīng)的文件存在,并且是一個(gè)文件,則直接刪除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("刪除單個(gè)文件" + fileName + "成功!");
            } else {
                System.out.println("刪除單個(gè)文件" + fileName + "失?。?);
            }
        } else {
            System.out.println("刪除單個(gè)文件失?。? + fileName + "不存在!");
        }
    }

}

EchartsUtil.java:將option轉(zhuǎn)化為圖片編碼base64

/**
 * <h3>demo</h3>
 * <p></p>
 *
 * @author : dkl
 * @date : 2023-05-12 14:07
 **/
public class EchartsUtil {
//    private static String url = "http://localhost:6666";

    private static final String SUCCESS_CODE = "1";

    public static String generateEchartsBase64(String option, String url) 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 = JSONObject.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;
    }
}

生成柱狀圖文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-595934.html

 /**
     * 生成單柱狀圖
     * @param //isHorizontal 是否水平放置
     * @param //color  柱狀圖顏色,可以不設(shè)置,默認(rèn)為紅色
     * @param //title  柱狀圖標(biāo)題
     * @param //xdatas  橫軸數(shù)據(jù)
     * @param //ydatas  縱軸數(shù)據(jù)
     * @return
     */
    public static GsonOption createBar(BarData barData){
        String title = barData.getTitle();
        boolean isHorizontal = barData.getIsHorizontal();
        Object[] xdatas = barData.getBarParamList().getBarName();
        Object[] ydatas = barData.getBarParamList().getBarValue();
        String legendName = barData.getBarParamList().getLegendName();

        Bar bar = new Bar();  //圖類(lèi)別(柱狀圖)
        //title
        EnhancedOption option = new EnhancedOption();
        option.title(title);  //標(biāo)題
        option.title().textStyle().fontSize(15).color("#000000").fontWeight("bolder");

        //工具欄 toolbox
        option.toolbox().show(true).feature(Tool.mark,  //輔助線(xiàn)
                Tool.dataView, //數(shù)據(jù)視圖
                new MagicType(Magic.line, Magic.bar), //線(xiàn)圖,柱狀圖切換
                Tool.restore, //還原
                Tool.saveAsImage   //保存圖片
        );
        option.toolbox().show(true).feature();

        //tooltip
        option.tooltip().show(true).formatter("{a}<br/> : {c}");  //顯示工具提示,設(shè)置提示格式

        //legend
        Legend legend = new Legend();
        TextStyle textStyle = new TextStyle();
        textStyle.color("red");
        textStyle.fontSize(10);
        textStyle.fontWeight("bolder");
        legend.setData(Collections.singletonList(legendName));
        legend.setTextStyle(textStyle);
//        legend.setBorderWidth(100);
        option.setLegend(legend);  //圖例

        //axisLabel
        AxisLabel axisLabel = new AxisLabel();
        TextStyle textStyle1 = new TextStyle();
        textStyle1.fontSize(10);
        textStyle1.fontWeight("bolder");
        axisLabel.show(true);
        axisLabel.textStyle(textStyle1);
        axisLabel.setRotate(40);
        axisLabel.setInterval(0);

        //axisLine
        AxisLine axisLine = new AxisLine();
        LineStyle lineStyle = new LineStyle();
        lineStyle.color("#000000");
        lineStyle.width(4);
        axisLine.lineStyle(lineStyle);


        //xAxis
        CategoryAxis category = new CategoryAxis();// 軸分類(lèi)
        category.data(xdatas);// 軸數(shù)據(jù)類(lèi)別
        category.axisLabel(axisLabel);  // x軸文字樣式
        category.axisLine(axisLine);  //x軸樣式



        //yAxis
        ValueAxis valueAxis = new ValueAxis();
        valueAxis.setName("次數(shù)");
        valueAxis.axisLabel().show(true).textStyle().fontSize(15).fontWeight("bolder");  //y軸文字樣式
        valueAxis.axisLine().lineStyle().color("#315070").width(4);  //y軸樣式

        //series
        bar.name(legendName);

        Normal normal = new Normal();
        normal.setShow(true);
        if(barData.getIsHorizontal() == false){
            normal.position(Position.inside);
        }else {
            normal.position(Position.top);
        }
        normal.color("green");
        normal.textStyle().color("red").fontSize(15).fontWeight("bolder");
        bar.setBarWidth("70");  //柱條寬度
//        bar.setBarMaxWidth(100);  //柱條最大寬度
        //bar.setBarMinHeight(10);  //柱條最小高度
        bar.label().normal(normal);

        //循環(huán)數(shù)據(jù)
        for(int i = 0;i < xdatas.length;i++){
            int data = (int) ydatas[i];
            String color = "rgb(251,153,2)";
            //類(lèi)目對(duì)應(yīng)的柱狀圖
            Map<String, Object> map = new HashMap<>(2);
            map.put("value", data);

            map.put("itemStyle", new ItemStyle().normal(new Normal().color(color)));

            bar.data(map);
        }
        if(isHorizontal){  //橫軸為類(lèi)別,縱軸為值
            option.xAxis(category);  //x軸
            option.yAxis(valueAxis);  //y軸
        }else {  //橫軸為值,縱軸為類(lèi)別
            option.xAxis(valueAxis);  //x軸
            option.yAxis(category);  //y軸
        }

        option.series(bar);

        return option;
    }
  1. 啟動(dòng)測(cè)試
/**
 * <h3>demo</h3>
 * <p></p>
 *  * @author : dkl
 * @date : 2023-05-12 14:09
 **/
@Slf4j
public class EchartBar {
    private static   String  requestUrl= "http://127.0.0.1:6666";
    private static   String  imgUrl= "F:/";
    public static void main(String[] args) {
        BarData barData = new BarData();
        barData.setTitle("Test");
        barData.setIsHorizontal(true);
        BarParam barParam = new BarParam();
        String[] columnKeys = {"Test1","Test2","Test3","Test4","Test5","Test6","Test7"};
        barParam.setBarName(columnKeys);
        Object[] data ={1,9,0,15,9,3,4};
        barParam.setBarValue(data);
        barData.setBarParamList(barParam);

        GsonOption option = createBar(barData);
        String optionStr = JSONObject.toJSONString(option);
        log.error(optionStr);

        if(optionStr == null || "".equals(optionStr)){
            return;
        }
        try {
            String base64 =  EchartsUtil.generateEchartsBase64(optionStr, requestUrl);
            log.info("base64:" + base64);
            long nowStr = Calendar.getInstance().getTimeInMillis();
            //圖片名
            String imageName =  JDate.getDuanshijian(new JDate(),"yyyy-MM-dd_HH_mm_ss") +".png";
            log.info("bar圖片:" + imageName);
            File oldfile = FileUtil.generateImage(base64, imgUrl+imageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 生成圖片展示
    java生成echarts圖表,java,echarts,開(kāi)發(fā)語(yǔ)言

兩種方案到這就都實(shí)現(xiàn)了,來(lái)講一下這兩種的優(yōu)缺點(diǎn)吧

  • JFreeChart 方便快捷,不需要自己去安裝啟動(dòng)什么服務(wù),而Echarts插件需要安裝啟動(dòng)一個(gè)服務(wù)
  • JFreeChart 生成的圖片清晰度感覺(jué)不是很清晰,Echarts的X軸字符太多導(dǎo)致展示不齊全

以上是個(gè)人覺(jué)得,不詆毀??赡苁俏覜](méi)有細(xì)去研究,有知道解決方案的可以指導(dǎo)一下,上面有什么地方不懂的可以評(píng)論,看到必回的,讓兄弟們不要在里面碰壁。

到了這里,關(guān)于Java生成Echarts表圖的兩種方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀(guān)點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • python讀取Excel繪制餅圖的兩種方式

    python讀取Excel繪制餅圖的兩種方式

    matplotlib 簡(jiǎn)單方便,適合數(shù)據(jù)作圖或科學(xué)作圖(論文發(fā)表) pyecharts 流程略復(fù)雜,但功能強(qiáng)大,圖形具有交互式,適合項(xiàng)目開(kāi)發(fā)或商業(yè)分析報(bào)告,但是 它是一個(gè)非常新的庫(kù),開(kāi)發(fā)不穩(wěn)定 本文介紹用 pandas庫(kù) 讀取Excel (csv)數(shù)據(jù),分別用 matplotlib庫(kù) 和 pyecharts庫(kù) 繪制餅圖。 注: 實(shí)

    2024年02月11日
    瀏覽(23)
  • Android Studio 顯示gif動(dòng)圖的兩種方式

    Android Studio 顯示gif動(dòng)圖的兩種方式

    將所需的.gif圖片復(fù)制到drawable文件夾下,如下圖所示。 在布局文件添加ImageView代碼段,如下所示。 在MainActivity添加邏輯代碼段,如下所示。 將下載的glide-3-6-0.jar復(fù)制到Project視圖下的app-libs文件夾中,并右鍵選擇Add As library導(dǎo)入包,如下圖所示。 glide-3-6-0.jar的下載鏈接:htt

    2024年02月16日
    瀏覽(25)
  • java關(guān)閉流的兩種方法

    java關(guān)閉流的兩種方法

    當(dāng)使用完流后,關(guān)閉所有打開(kāi)的流仍然是一個(gè)好習(xí)慣。一個(gè)被打開(kāi)的流有可能會(huì)用盡系統(tǒng)的資源,這取決于平臺(tái)和實(shí)現(xiàn)。如果沒(méi)有將流關(guān)閉,另一個(gè)程序試圖打開(kāi)另一個(gè)流時(shí),可能會(huì)得到不需要的資源。 有兩種關(guān)閉方式: ? 如下: jdk1.7之前 方法一:手動(dòng)關(guān)閉,即為使用c

    2024年02月13日
    瀏覽(26)
  • Java開(kāi)啟異步的兩種方式

    Java開(kāi)啟異步的兩種方式

    必須配置異步線(xiàn)程池,否則異步不會(huì)生效。 @EnableAsync 注解:指定異步線(xiàn)程池。不指定默認(rèn)使用:SimpleAsyncTaskExecutor線(xiàn)程池 SimpleAsyncTaskExecutor是一個(gè)最簡(jiǎn)單的線(xiàn)程池,它沒(méi)有任何的線(xiàn)程相關(guān)參數(shù)配置,它會(huì)為每個(gè)任務(wù)創(chuàng)建一個(gè)新的線(xiàn)程來(lái)執(zhí)行,因此不建議在生產(chǎn)環(huán)境中使用。

    2024年02月06日
    瀏覽(24)
  • java 數(shù)組新增元素的兩種方法

    數(shù)組在使用前,長(zhǎng)度就已固定,所以原數(shù)組長(zhǎng)度是不能再改變了,基于此,提供如下兩種方式,添加元素?cái)?shù)據(jù) 1創(chuàng)建一個(gè)新數(shù)組,長(zhǎng)度為原數(shù)組加1,然后將原數(shù)組數(shù)據(jù)添加到新數(shù)組,最后再添加需要的新數(shù)據(jù) ????????String[] s1 = {\\\"a\\\",\\\"b\\\",\\\"c\\\"}; ? ? ? ? String[] s2 = new String[s1.l

    2024年02月16日
    瀏覽(23)
  • java 數(shù)組添加元素的兩種方法

    說(shuō)在前面 數(shù)組在使用前,長(zhǎng)度就已固定,所以原數(shù)組長(zhǎng)度是不能再改變了,基于此,提供如下兩種方式,給數(shù)組添加數(shù)據(jù)。具體代碼如下 方式一: 創(chuàng)建一個(gè)新數(shù)組,長(zhǎng)度為原數(shù)組加1,然后將原數(shù)組數(shù)據(jù)添加到新數(shù)組,最后再添加需要的新數(shù)據(jù) 運(yùn)行結(jié)果 方式二: 先把數(shù)組轉(zhuǎn)

    2024年02月11日
    瀏覽(28)
  • Java 獲取小程序碼的兩種方式

    目前小程序推出了自己的識(shí)別碼,小程序碼, 圓形的碼看起來(lái)比二維碼好看。 本文總結(jié)微信小程序的獲取小程序二維碼的接口開(kāi)發(fā)。官方地址 主要內(nèi)容摘抄自微信小程序的API文檔,java接口開(kāi)發(fā)是自己總結(jié)開(kāi)發(fā)。 通過(guò)后臺(tái)接口可以獲取小程序任意頁(yè)面的二維碼,掃描該二維

    2024年02月14日
    瀏覽(24)
  • Java基礎(chǔ):Collections.sort的兩種用法詳解

    Collections是?個(gè)?具類(lèi),sort是其中的靜態(tài)?法,是?來(lái)對(duì) List 類(lèi)型進(jìn)?排序的,它有兩種參數(shù)形式:

    2024年02月10日
    瀏覽(24)
  • 讓小程序動(dòng)起來(lái)-輪播圖的兩種方式--【淺入深出系列003】

    讓小程序動(dòng)起來(lái)-輪播圖的兩種方式--【淺入深出系列003】

    微信目錄集鏈接在此: 詳細(xì)解析黑馬微信小程序視頻–【思維導(dǎo)圖知識(shí)范圍】 難度★???? 不會(huì)導(dǎo)入/打開(kāi)小程序的看這里:參考 讓別人的小程序長(zhǎng)成自己的樣子-更換window上下顏色–【淺入深出系列001】 用免費(fèi)公開(kāi)視頻,卷飛培訓(xùn)班哈人!打死不報(bào)班,賺錢(qián)靠狠干! 只

    2024年02月16日
    瀏覽(20)
  • Java簡(jiǎn)化MongoDB編解碼器的兩種方法

    在與MongoDB進(jìn)行數(shù)據(jù)交互時(shí),有時(shí)候會(huì)遇到找不到類(lèi)的編解碼器(codec)的錯(cuò)誤。為了解決這個(gè)問(wèn)題,一種常見(jiàn)的方法是創(chuàng)建自定義編解碼器來(lái)處理特定的類(lèi)。然而,對(duì)于一些開(kāi)發(fā)者來(lái)說(shuō),這樣的方法可能過(guò)于繁瑣。本文將介紹兩種簡(jiǎn)化MongoDB編解碼器的方法,讓您能夠更輕松地

    2024年02月15日
    瀏覽(19)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包