Today the head a bit of pain, so can not be written in detail, first put the code up, and other physical conditions a little better, and then continue to improve.
1. (lead) A tool class that generates Anychart XML data using an XML template
/** * */package com.common.anychart;import java.io.inputstream;import Java.util.list;import Org.apache.commons.collections.collectionutils;import Org.apache.commons.lang.nullargumentexception;import Org.apache.commons.lang.stringutils;import Org.apache.log4j.logger;import Org.dom4j.document;import Org.dom4j.element;import org.dom4j.io.saxreader;import com.common.reflect.reflectutils;/** * XML data Processing tool class, Service to Anychart Report * @author Luolin * * @version $id: anychartxmlprocessor.java,v 0.1 August 19, 2015 morning 10:15:57 Luolin EXP $ */publi C class Anychartxmlprocessor {private static final Logger Logger = Logger . GetLogger (Anychartxmlprocessor.class); /** simple Linear curve template path */private static final String Simple_line_template_file = "Xmltemplate/simpleline.xml"; /** Simple Histogram template path */private static final String Simple_histogram_template_file = "Xmltemplate/simplehistogram.xml"; /** * Using Simpleline.xml MoldThe board generates a simple linear graph of the XML data * @param xName X-axis title, formatted as: "x-axis title @feild", Feild represents the field from which the data was taken * @param yname y-axis title, formatted as: "Y-axis title @feild", Feild table * @param title icon title * @param dataList the data to be displayed * @return generated XML data * @throws Exception * * public static string Simpleline (String xName, String yname, string title, List<?> dataList) Throws Exception {logger.info ("" Using categorize Dvertical.xml template generates a simple linear graph of XML data "XName:" + XName + ", Yname:" + Yname + ", Title:" + title "; Basic parameter Check if (!basedatavalidate (XName, Yname, title, dataList)) {return ""; } string[] XData = Xname.split ("@"); string[] Ydata = Yname.split ("@"); Axis data Check axisformatvalidate (XData, ydata); InputStream InputStream = AnyChartXMLProcessor.class.getClassLoader (). getResourceAsStream (simple_line_template _file); Return Templateprocessor (title, DataList, XData, Ydata, InputStream); /** * Process data according to the template, generate modified XML data * @param title of the title of the chart * @param dataList statistics * @param xData X-axis data * @pa Ram Ydata Y-axis data * @param inputstream The stream that is read into the template * @return the XML data obtained after modifying the template * @throws Exception */@SuppressWarn Ings ("unchecked") private static string Templateprocessor (String title, list<?> dataList, string[] XData, String[] Ydata, InputStream InputStream) Throws Exception {saxreader sax = new Saxreader (); Document xmldoc = Sax.read (InputStream); Element root = Xmldoc.getrootelement ();//root node//Get text node list<element> titleelements = Root.selectno Des ("//text"); Get the first text node under Chart_settings and modify its value Element titleelement = titleelements.get (0); Titleelement.settext (title); Get XThe first text coordinate of the axis, modifying its value Element xtitleelement = titleelements.get (1); Xtitleelement.settext (Xdata[0]); Get the first text coordinate of the x-axis, modify its value Element ytitleelement = Titleelements.get (2); String ytitletemplate = Ytitleelement.gettexttrim (); Ytitleelement.settext (Ytitletemplate.replace ("#YTitle #", Ydata[0])); Replace the title of x, y in format list<element> formatelements = Root.selectnodes ("//format"); if (Collectionutils.isnotempty (formatelements)) {for (Element element:formatelements) {Strin G Formattext = Element.gettexttrim (); Element.settext (Formattext.replace ("#YTitle #", Ydata[0]). Replace ("#XTitle #", Xdata[0])); }} Element Dataelement = (Element) Root.selectsinglenode ("//data"); How datasets are stored in more datasets (indicating that multiple lines or columns are required), looping if (datalist.get (0) instanceof List) {for (Object Element:datali ST) {createserieselement (title, (list<? >) element, XData, Ydata, dataelement); } return Xmldoc.asxml (); } createserieselement (title, DataList, XData, Ydata, dataelement); return Xmldoc.asxml (); }/** * Generates series part * @param title title * @param dataList Data collection * @param xData X-Axis data * @param ydata y-axis data * @param dataelement "Data" Node * @throws Exception */private static void Createserieselement (String title, List<?> dataList, string[] xData, string[] ydata, Element dataelement) t Hrows Exception {Element serieselement = dataelement.addelement ("series"); Serieselement.addattribute ("name", title); for (Object item:datalist) {Element pointelement = serieselement.addelement ("point"); Pointelement.addattribute ("Name", String.valueof (Reflectutils.getcellvalue (item, xdata[1])); Pointelement.addattribute ("Y", String.vaLueof (Reflectutils.getcellvalue (item, ydata[1])); }}/** * Axis data Check * @param xData X-Axis information * @param ydata y-Axis information */private static void Axisformatvalida Te (string[] xData, string[] ydata) {if (Xdata.length < 2) {Logger.warn ("" XName parameter Incorrect "XData:" + xDa TA); throw new IllegalArgumentException ("XName"); } if (Ydata.length < 2) {Logger.warn ("" Yname parameter is incorrect "Ydata:" + ydata); throw new IllegalArgumentException ("Yname"); }}/** * Basic data Check * @param xName x axis title, format such as: "X axis title @feild", Feild represents the field from the data to be taken from the value of * @param yname y-axis title, format as: "Y-axis title @fei LD ", Feild represents the field from which the data is valued * @param title icon title * @param dataList the data to be displayed */private static Boolean Basedatavalidat E (String xName, String yname, string title, List<?> dataList) {if (Collectionutils.isempty (DataList)) {Logger.warn ("" Data DataList is Empty ""); return false; } if (Stringutils.isblank (XName)) {Logger.warn ("" XName is Empty "); throw new Nullargumentexception ("XName"); } if (Stringutils.isblank (Yname)) {Logger.warn ("" Yname is Empty "); throw new Nullargumentexception ("Yname"); } if (Stringutils.isblank (title)) {Logger.warn ("" "Title is empty"); throw new Nullargumentexception ("title"); } return true; /** * Use the Simplehistogram.xml template to generate XML data for a simple histogram * @param xName X-axis title, in the form of "x-axis caption @feild", Feild represents the field from which the value is taken from the data * @para M yname Y-axis title, formatted as: "Y-axis title @feild", Feild represents the field from which the data is valued * @param title icon title * @param dataList data to show * @return generated XML data * @throws Exception */public static string Simplehistogram (String xName, String yname, string title, List< ;? > dataList) throws E xception {logger.info ("" uses the Simplehistogram.xml template to generate a simple columnXML data "XName:" + XName + ", Yname:" + Yname + ", Title:" + title "; Basic parameter Check if (!basedatavalidate (XName, Yname, title, dataList)) {return ""; } string[] XData = Xname.split ("@"); string[] Ydata = Yname.split ("@"); Axis data Check axisformatvalidate (XData, ydata); InputStream InputStream = AnyChartXMLProcessor.class.getClassLoader (). getResourceAsStream (Simple_histogram_tem Plate_file); Return Templateprocessor (title, DataList, XData, Ydata, InputStream); }/** * Use the Simplehistogram.xml template to generate XML data for a simple multi-column histogram * @param xName X-axis title, in the form of "x-axis caption @feild", Feild represents the field from which the value is taken from the data * @pa Ram Yname Y-axis title, formatted as: "Y-axis title @feild", Feild represents the field from which the data is valued * @param title icon title * @param dataList data to show * @return generated XML Data * @throws Exception */public static string Comparehistogram (String xName, String yname, string title, List<list<?>>DataList) throws Exception {Logger.info ("" Using Simplehistogram.xml template to generate XML data for a simple multi-column histogram "XName:" + XName + ", Yname: "+ Yname +", Title: "+ title"; Basic parameter Check if (!basedatavalidate (XName, Yname, title, dataList)) {return ""; } string[] XData = Xname.split ("@"); string[] Ydata = Yname.split ("@"); Axis data Check axisformatvalidate (XData, ydata); InputStream InputStream = AnyChartXMLProcessor.class.getClassLoader (). getResourceAsStream (Simple_histogram_tem Plate_file); Return Templateprocessor (title, DataList, XData, Ydata, InputStream); }}
2. template file: Currently I use two simple template files. Friends in use, pay attention to the template relative to the project path needs to be modified according to the actual situation.
Line chart template (simpleline.xml):
<anychart><settings><animation enabled= "True"/></settings><charts><chart plot_ Type= "categorizedvertical" ><chart_settings><title enabled= "true" ><text> title uninitialized </text> </title><axes><x_axis tickmarks_placement= "Center" ><labels enabled= "true" rotation= "60" Display_mode= "Rotated" align= "Inside" > </labels> <title enabled= "true" ><text> #XTitle #</ Text></title></x_axis><y_axis><title enabled= "true" ><text> #YTitle #: {%min}-{% Max}</text></title></y_axis></axes></chart_settings><data_plot_settings Default_series_type= "line" ><line_series point_padding= "0.2" group_padding= "1" ><label_settings enabled = "true" ><background enabled= "false"/><font color= "RGB (45,45,45)" bold= "true" size= "9" ><effects Enabled= "true" ><glow enabled= "true" color= "White" opacity= "1" blur_x= "1.5" blur_y= "1.5" strength= "3"/></effects></font><format>{%YValue}{numDecimals:0}</format></label_settings>< Tooltip_settings enabled= "true" ><format> #YTitle #: {%yvalue}{numdecimals:2} #XTitle #: {%name}</format ><background><border type= "Solid" color= "Darkcolor (%color)"/></background><font color= " Darkcolor (%color) "/></tooltip_settings><marker_settings enabled=" true "/><line_style>< Line thickness= "3"/></line_style></line_series></data_plot_settings><data></data ></chart></charts></anychart>
Bar chart Template (Simplehistogram.xml):
<anychart><settings><animation enabled= "True"/></settings><charts><chart plot_ Type= "categorizedvertical" ><chart_settings><title enabled= "true" ><text> title uninitialized </text> </title><axes><x_axis tickmarks_placement= "Center" ><labels enabled= "true" rotation= "60" Display_mode= "Rotated" align= "Inside" > </labels> <title enabled= "true" ><text> #XTitle #</ Text></title></x_axis><y_axis><title enabled= "true" ><text> #YTitle #: {%min}-{% Max}</text></title></y_axis></axes></chart_settings><data_plot_settings Default_series_type= "Bar" ><bar_series group_padding= "0.2" ><tooltip_settings enabled= "true" >< Format> #YTitle #: {%yvalue}{numdecimals:2} #XTitle #: {%name}</format><background><border type= " Solid "color=" Darkcolor (%color) "/></background><font color=" Darkcolor (%color) "/></tooltip_ Settings></bar_series></data_plot_settings><data></data></chart></charts>< /anychart>
3, how to use?
I used Ajax to get the XML data and give it to Anychart.
/** * Create chart * @param chartdivid the ID of the div that displays the chart * @param xmlData chart requires XML data */function Createchart (chartdivid,xmldata) {Anychart . Swffile = ".. /js/anychart/anychart.swf "; Anychart.inittext = "Initialize, please later ..."; Anychart.xmlloadingtext = "Data loading, please later ..."; Anychart.nodatatext = "No data display, change the query conditions to try!" "; var g_dxzr_chart = new Anychart (); g_dxzr_chart.width = ' 100% '; g_dxzr_chart.height = ' 100% '; g_dxzr_chart.bgcolor =" # FFFFFF "; G_dxzr_chart.setdata (XmlData); G_dxzr_chart.write (Chartdivid);} /** * Get Data * @param top3formid the ID of the form of the query parameter */function executeAnalyzeTop3 (top3formid,chartdivid) {var $form = $ (' # ' +TOP3FO RMID); $.ajax ({url: $form. attr (' action '), data: $form. Serialize (), DataType: ' Text ', type: ' Post ', success:function (data) {// Create Chart Createchart (Chartdivid,data);},error:function () {alert (' system exception, please contact Administrator! ‘);}})}
If you have any problem, you can give me a message, I also recently came into contact with the Anychart, the effect actually feel good.
We all study progress together.
Combine Anychart to make a report: A tool class for generating Anychart graphical XML data