java后臺(tái)生成統(tǒng)計(jì)圖
以下是【錦鯉飛上天】分享的內(nèi)容全文:
java后臺(tái)生成統(tǒng)計(jì)圖
在后臺(tái)生成Echarts統(tǒng)計(jì)圖,然后放到pdf中,當(dāng)時(shí)聽(tīng)到這個(gè)需求的時(shí)候很懵,其實(shí)可以讓前端把圖片下載下來(lái)傳給后端的,奈何不是一個(gè)頁(yè)面啊,所以為了不必要的麻煩,也是提升自己的業(yè)務(wù)能力,就自己搞一下吧!
這篇文章主要是用來(lái)介紹如何通過(guò)后臺(tái)生成Echarts統(tǒng)計(jì)圖,至于如何插入到pdf中,我會(huì)單獨(dú)寫(xiě)一篇文章來(lái)講解。
當(dāng)時(shí)剛接到這個(gè)需求的時(shí)候無(wú)從下手,不知道如何去用后臺(tái)生Echars統(tǒng)計(jì)圖,后來(lái)也是找了半天資料又是百度的總算找到了解決方法,而且現(xiàn)在大家粘貼問(wèn)題的手法都一樣,有的資料是有用的有的純屬就是把人家解決過(guò)的復(fù)制過(guò)來(lái),我試了試不是缺這就是缺那,當(dāng)然也可能是我能力不行,讀不懂人家的代碼。哈哈,所以只能自己整合整合寫(xiě)一個(gè)完整版生成的文章了,好了不廢話了下面上解決方案吧!
我找了兩種方法,第一種是使用jfreechart實(shí)現(xiàn),另一種是通過(guò)一些小的工具實(shí)現(xiàn)
一、 jfreechart實(shí)現(xiàn)統(tǒng)計(jì)圖(jfreechart實(shí)現(xiàn)的統(tǒng)計(jì)圖有點(diǎn)丑不過(guò)比較簡(jiǎn)單)
1、首先引入pom依賴
<!--用于jfreechart生成圖片 --> <dependency> <groupId>org.jfree</groupId> <artifactId>jfreechart</artifactId> <version>1.5.0</version> </dependency>
2、基本上這一個(gè)類就能直接生成了比較簡(jiǎn)單
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 = "暫無(wú)數(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);// 溫度計(jì)
ChartFactory.setChartTheme(chartTheme);
}
public ChartUtils() {
}
/**
* 必須設(shè)置文本抗鋸齒
*/
public static void setAntiAlias(JFreeChart chart) {
chart.setTextAntiAlias(false);
}
/**
* 設(shè)置圖例無(wú)邊框,默認(rèn)黑色邊框
*/
public static void setLegendEmptyBorder(JFreeChart chart) {
chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
}
/**
* 提供靜態(tài)方法:獲取報(bào)表圖形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,中文將顯示不出來(lái)
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()));
}
/**
* 生成一個(gè)餅圖的圖表
* 分別是:顯示圖表的標(biāo)題、需要提供對(duì)應(yīng)圖表的DateSet對(duì)象、是否顯示圖例、是否生成貼士以及是否生成URL鏈接
*/
JFreeChart chart = ChartFactory.createPieChart(title, pds, true, true, true);
setPieRender((PiePlot) chart.getPlot());
//將內(nèi)存中的圖片寫(xiě)到本地硬盤(pán)
org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart,800,500);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 提供靜態(tài)方法:獲取報(bào)表圖形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,中文將顯示不出來(lái)
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());
}
/**
* 生成一個(gè)餅圖的圖表
* 分別是:顯示圖表的標(biāo)題、需要提供對(duì)應(yīng)圖表的DateSet對(duì)象、是否顯示圖例、是否生成貼士以及是否生成URL鏈接
*/
JFreeChart chart = ChartFactory.createBarChart(title,"分類","數(shù)量", pds, PlotOrientation.VERTICAL, true, true, false);
//將內(nèi)存中的圖片寫(xiě)到本地硬盤(pán)
org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart,800,500);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 提供靜態(tài)方法:獲取報(bào)表圖形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, // 是否顯示圖例(對(duì)于簡(jiǎn)單的柱狀圖必須是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ù)點(diǎn)繪制形狀
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);// 簡(jiǎn)單標(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í)防止數(shù)據(jù)無(wú)法顯示
*
* @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ù)無(wú)法顯示
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í)防止數(shù)據(jù)無(wú)法顯示
*
* @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ù)無(wú)法顯示
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)計(jì)結(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日金額(日?qǐng)?bào))",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)計(jì)結(jié)果", map2,"E:\\data\\cc.jpg");
}
}這是生成的圖片,除了樣式簡(jiǎn)單一點(diǎn),是可以滿足正常需求的



二、 phantomjs + echarts-convert生成Echarts圖片
首先先把這兩個(gè)三方的下載地址鏈接出來(lái)
phantomjs下載地址:https://phantomjs.org/download.html
echarts-convert下載地址:見(jiàn)附件
下載下來(lái)以后,需要配置phantomjs的環(huán)境變量,
直接在path中加一下就行,D:\phantomjs-2.1.1-windows\bin,這是我的文件路徑,也是環(huán)境變量配置的路徑
完整信息見(jiàn)附件!
本站不存儲(chǔ)任何資源文件,敬請(qǐng)周知!
本網(wǎng)站采用 BY-NC-SA 協(xié)議進(jìn)行授權(quán) 轉(zhuǎn)載請(qǐng)注明原文鏈接:java后臺(tái)生成統(tǒng)計(jì)圖

侵權(quán)舉報(bào)/版權(quán)申訴



