1. 程式人生 > >echarts動態載入資料,顯示柱狀圖,餅圖圖表

echarts動態載入資料,顯示柱狀圖,餅圖圖表

第一次寫部落格,有點小激動。公司正在開發的web版固定資產管理軟體,需要做報表,需要直觀的顯示一些領導感興趣的資料。就想到百度的echarts啦,關於echarts的更多資訊請移步echarts首頁

 言歸正傳。第一步,在jsp頁面,需要引入esl.js,是一個瀏覽器端、符合AMD的標準載入器,適合用於現代Web瀏覽器端應用的入口與模組管理(必須要引入)。如我的專案“<script type="text/javascript" src="${rootPath}/capital_assets/common/echarts/esl.js" ></script>”。第二部,在專案中加入echarts包和zrender包,兩者的包必須在同一目錄下,如:


下面是我的JSP頁面:

<script type="text/javascript" src="${rootPath}/capital_assets/common/echarts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="${rootPath}/capital_assets/common/echarts/esl.js" ></script>
<script type="text/javascript">
		//配置路徑
		require.config({
			packages:[
				{  
				    name: 'zrender',  
				    location: '../common/zrender/src', // zrender與echarts在同一級目錄  
				    main: 'zrender'  
				},  
				{  
				    name: 'echarts',  
				    location: '../common/echarts2.2.7/src',  
				    main: 'echarts'  
				}      
			]
		});
		
		// 按需載入(需要用什麼圖示就引入包,如柱狀圖:'echarts/chart/bar',)
		require(
			[
			 	'echarts', 
			 	'echarts/chart/bar',
			 	'echarts/chart/pie'
			],
			function (ec) {
				var chart1=document.getElementById('chart1');
				var echart1 = ec.init(chart1);
				var chart2  = document.getElementById('chart2');
				var echart2 = ec.init(chart2);
				var categories = [];
				var values = [];
				var orgs=[];
				var orgVal=[];
				$.ajaxSettings.async = false;
				// 載入資料
				$.getJSON("${request.pageContext.contextPath}/capital_assets/reporter/reporter_classfy.action", function (json) {
					categories = json.categories;
					values = json.values;
					orgs=json.orgs;
					orgVal=json.orgVal;
				});
				var option1={
						backgroundColor:'rgba(12,121,123,0.1)',
						title : {
					        text: '資產概覽',
					        subtext: '餅圖',
					        x:'center',
					        backgroundColor:'rgba(12,121,123,0.1)'
					      },
					      tooltip : {
					        trigger: 'item',
					        formatter: "{a} <br/>{b} : {c} ({d}%)"
					      },
					      legend: {
					        orient : 'vertical',
					        x : 'left',
					        data:categories,
					      },
					      toolbox: {
					        show : true,
					        feature : {
					          restore : {show: true},
					        }
					      },
					      calculable : true,
					      series : [
					        {
					          name:'詳情',
					          type:'pie',
					          radius : '55%',
					          center: ['50%', '60%'],
					          data: (function(){
	                                var res = [];
	                                var len = values.length;
	                                while (len--) {
		                                res.push({
		                                name: categories[len],
		                                value: values[len]
	                                });
	                                }
	                                return res;
	                                })()
					        }
					      ]	
				};
				var option2 = {
						title:{
							text:'資產科室分佈',
							subtext:'柱狀圖',
							x:'center'
						},
						grid:{
							x:80,
							y:80,
							x2:80,
							y2:80
						},
						tooltip: {
							show: true
						},
						legend: {
							orient :'vertical',
					        x : 'left',
					        data:['科室總資產'],
						},
						xAxis: [
						    {
						    	type: 'category',
						    	data: orgs
						    }
						],
						yAxis: [
						    {
						    	type: 'value'
						    }
						],
						series: [
						    {
						    	'name': '詳情',
						    	'type': 'bar',
						    	'data': orgVal,
						        'itemStyle': {
					                'normal': {
					                   		color: function(params) {
						                        var colorList = [
						                          '#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
						                           '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
						                           '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
						                        ];
					                        	return colorList[params.dataIndex];
					                    	},
						                    label:{
						                        show: true,
						                        position: 'top',
						                        formatter: '{b}\n{c}'
						                    }
					                 }
						        }
						    }
						]
					};
				echart1.setOption(option1);
				echart2.setOption(option2);
			}
		);
	</script>
</head>
<body>
	<div id="chart1" style="height:500px;"></div><br/><hr>
	<div id="chart2" style="height:500px;"></div>
</body>
</html>

通過上面的程式碼,我們可以看出,頁面通過ajax請求action(servlet)接受返回的json格式資料,然後進行圖表資訊的構建。我的action中部分程式碼如下:

<span style="font-size:18px;">public String classfy() throws IOException{
		HttpServletResponse response=getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		<span style="background-color: rgb(255, 255, 255);">
		<span style="color:#FF0000;">Map<String, Object> json = new HashMap<String, Object>();  
		int i=reporterService.getTotalClassfy();
		String[] classfies=reporterService.getZCFLName();
		json.put("categories", classfies);  </span></span>
		try{
			double[] values=reporterService.getCountByName();
			json.put("values", values);  
		}catch(Exception e) {
			log.info("Service.getCountByName()從配置檔案讀取sql語句出現異常");
			e.printStackTrace();
			return null;
		}
		<span style="color:#FF0000;">String[] orgs=reporterService.getOrgNames();
		json.put("orgs",orgs);
		double[] orgVal=reporterService.getCountByOrgName();
		json.put("orgVal",orgVal);</span>
		
                out.write(JSONObject.fromObject(json).toString());
		return null;
	}</span>

上邊標紅的為核心程式碼。到此,就可以完整顯示啦。效果圖: