jfreechart生成報表(定時器中)
阿新 • • 發佈:2018-12-23
TimingListener中
DealCountTask 中<span style="font-size:18px;">public class TimingListener implements ServletContextListener { private Timer timer = null; public void contextInitialized(ServletContextEvent event) { timer = new Timer(true); try{ //成交量定時查詢啟動(有發) this.dealCount(); }catch(Exception e){ e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent event) { timer.cancel(); } //每天00:30執行 public void dealCount(){ timer = new Timer(true); Calendar theTaskCalendar = Calendar.getInstance(); theTaskCalendar.set(theTaskCalendar.HOUR_OF_DAY, 0); theTaskCalendar.set(theTaskCalendar.MINUTE, 30); theTaskCalendar.set(theTaskCalendar.SECOND, 0); long interval = 1000 * 60 * 60 * 60 * 24; // long interval = 1000 * 30; System.out.println("=============成交量定時查詢啟動============="); timer.schedule(new DealCountTask(interval),theTaskCalendar.getTime(), interval); } }</span>
TaskService 中<span style="font-size:18px;">public class DealCountTask extends TimerTask{ protected Log log; ArrayList list; long intervalTime; private Map map; public Map getMap() { return this.map; } public void setMap(Map map) { this.map = map; } public DealCountTask(long interval) { this.log = LogFactory.getLog(super.getClass()); this.intervalTime = interval; } public void run() { try { this.map = new HashMap(); this.map.put("switchType", "DS_00008"); ITaskService taskService = (ITaskService)SpringBeanProxy.getBean("taskService"); this.list = ((ArrayList)taskService.getPlatformList(this.map)); this.map.clear(); for(int j=0 ;j<list.size() ; j++){ this.map = (Map)this.list.get(j); if (this.map.get("switchValue").equals("1")) { HashMap param = new HashMap(); Date date=new Date(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); String nowDate=format.format(date); HashMap map1 = new HashMap(); //獲取platformId param.put("platformId", this.map.get("platformId")); //獲取品種 List list = new ArrayList(); list = taskService.getCategory(param); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); //周 昨天 到 今天-8 calendar.add(calendar.DATE, -8); Date rqs = calendar.getTime(); calendar.add(calendar.DATE, 7); Date rqe = calendar.getTime(); param.put("rqStart", format.format(rqs)); param.put("rqEnd", format.format(rqe)); //迴圈品種 for(int i=0;i<list.size();i++){ map1 = (HashMap) list.get(i); //獲取品種名 param.put("catalog_name" + i, map1.get("catalog_name")); param.put("catalog_name", map1.get("catalog_name")); map1 = taskService.getcount(param); param.put("categoryCountWeek" + i, map1.get("categoryCount")); } //月 calendar.add(calendar.MONTH, -1); rqs = calendar.getTime(); calendar.add(calendar.MONTH, 1); rqe = calendar.getTime(); param.put("rqStart", format.format(rqs)); param.put("rqEnd", format.format(rqe)); //迴圈品種 for(int i=0;i<list.size();i++){ map1 = (HashMap) list.get(i); //獲取品種名 param.put("catalog_name" + i, map1.get("catalog_name")); param.put("catalog_name", map1.get("catalog_name")); map1 = taskService.getcount(param); param.put("categoryCountMonth" + i, map1.get("categoryCount")); } //年 calendar.add(calendar.YEAR, -1); rqs = calendar.getTime(); calendar.add(calendar.YEAR, 1); calendar.add(calendar.DATE, -1); rqe = calendar.getTime(); param.put("rqStart", format.format(rqs)); param.put("rqEnd", format.format(rqe)); //迴圈品種 for(int i=0;i<list.size();i++){ map1 = (HashMap) list.get(i); //獲取品種名 param.put("catalog_name" + i, map1.get("catalog_name")); param.put("catalog_name", map1.get("catalog_name")); map1 = taskService.getcount(param); param.put("categoryCountYear" + i, map1.get("categoryCount")); } //生成jfreechart圖片(餅狀圖) String filename2 = ChartUtils.pieChart(param,list,"week"); param.put("filename2", filename2); String filename3 = ChartUtils.pieChart(param,list,"month"); param.put("filename3", filename3); String filename4 = ChartUtils.pieChart(param,list,"year"); param.put("filename4", filename4); param.put("outResult", "1"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("成交量定時查詢異常:" + e.getMessage()); } } }</span>
DA O中<span style="font-size:18px;">@Override public List getCategory(HashMap param) { List list = dao.queryMapList("json.getCategory", param); return list; } @Override public HashMap getcount(HashMap param) { HashMap map = (HashMap) dao.queryMap("json.getcount", param); return map; }</span>
<span style="font-size:18px;">public Map queryMap(String id, Object parameterObject) {
return (Map) getSqlMapClientTemplate().queryForObject(id,
parameterObject);
}
public Object queryObject(String id, Object parameterObject) {
return getSqlMapClientTemplate().queryForObject(id, parameterObject);
}</span>
json.xml中
<span style="font-size:18px;"><select id="json.getCategory" parameterClass="map" resultClass="java.util.HashMap">
SELECT DISTINCT v.catalog_name as catalog_name FROM v_catalog_order v WHERE v.platform_id = #platformId#
</select>
<select id="json.getcount" parameterClass="map" resultClass="java.util.HashMap">
SELECT
ROUND(IFNULL(sum(v.init_weight),0),2) AS categoryCount
FROM
v_catalog_order v
WHERE
v.catalog_name = #catalog_name#
AND date_format(v.create_date, '%Y-%m-%d') >= #rqStart#
AND date_format(v.create_date, '%Y-%m-%d') <= #rqEnd#
</select> </span>
ChartUtils中(jfreechart)
<span style="font-size:18px;">public class ChartUtils {
/**
* 使用Jfreechart生成圖片(柱狀圖)
* @return
*/
public static String generaterBarChart(HashMap map) {
//構造資料集合
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 4; i >= 0; i--) {
dataset.addValue(Double.parseDouble(map.get("dealCount" + i).toString()),"",map.get("date" + i).toString());
// dataset.addValue(i*1000, "日期", "0"+i);
}
JFreeChart chart = ChartFactory.createBarChart3D("", //圖形主標題 );
// 設定總的背景顏色
chart.setBackgroundPaint(ChartColor.WHITE);
// 獲得圖表物件
CategoryPlot p = chart.getCategoryPlot();
// 設定圖的背景顏色
p.setBackgroundPaint(ChartColor.WHITE);
//處理主標題亂碼
chart.getTitle().setFont(new Font("宋體",Font.BOLD,18));
//處理子標題的亂碼
chart.getLegend().setItemFont(new Font("宋體",Font.BOLD,15));
//處理X軸和Y軸的亂碼
//呼叫圖表區域物件(xxxxPlot)
CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
//獲取X軸的物件
CategoryAxis3D categoryAxis3D = (CategoryAxis3D) categoryPlot.getDomainAxis();
//獲取Y軸的物件
NumberAxis3D numberAxis3D = (NumberAxis3D) categoryPlot.getRangeAxis();
//處理X軸上的亂碼
categoryAxis3D.setTickLabelFont(new Font("宋體",Font.BOLD,15));
//處理X軸外的亂碼
categoryAxis3D.setLabelFont(new Font("宋體",Font.BOLD,15));
//處理Y軸上的亂碼
numberAxis3D.setTickLabelFont(new Font("宋體",Font.BOLD,15));
//處理Y軸外的亂碼
numberAxis3D.setLabelFont(new Font("宋體",Font.BOLD,15));
//設定y軸上的刻度的預設值為100
// numberAxis3D.setAutoTickUnitSelection(false);
// NumberTickUnit unit = new NumberTickUnit(100);
// numberAxis3D.setTickUnit(unit);
//呼叫繪圖區域物件(xxxxRenderer)
BarRenderer3D barRenderer3D = (BarRenderer3D) categoryPlot.getRenderer();
barRenderer3D.setSeriesPaint(0, Color.decode("#FF9E01"));
//使圖形變得苗條
barRenderer3D.setMaximumBarWidth(0.08);
//在圖形上生成數字
barRenderer3D.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
barRenderer3D.setBaseItemLabelsVisible(true);
barRenderer3D.setBaseItemLabelFont(new Font("宋體",Font.BOLD,15));
//要求使圖形chart生成圖片,在專案指定的chart資料夾下
//獲取專案chart資料夾的目錄
String path = new Property(Constant.propFilePath).getValue("reportUploadPath");//E:/temp/reppic/
//按照當前日期的年月日時分秒的形式生成圖片名稱
// String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
String filename = "dealCount.png";
//用Jfreechart生成的圖片放置到指定的chart的資料夾下
File file = new File(path+"/"+filename);
try {
ChartUtilities.saveChartAsJPEG(file, chart, 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
/**
* 餅狀圖
* @param map
* @param list
* @return
*/
public static String pieChart(HashMap map, List list,String flag) {
DefaultPieDataset dataset = new DefaultPieDataset();
String filename = "";
if (flag == "week") {
//周
for (int i = 0; i < list.size(); i++) {
dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountWeek" + i).toString()));
filename = "week.png";
}
}else if (flag == "month") {
//月
for (int i = 0; i < list.size(); i++) {
dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountMonth" + i).toString()));
filename = "month.png";
}
}else if (flag == "year") {
//年
for (int i = 0; i < list.size(); i++) {
dataset.setValue(map.get("catalog_name"+i).toString(), Double.parseDouble(map.get("categoryCountYear" + i).toString()));
filename = "year.png";
}
}
JFreeChart chart = ChartFactory.createPieChart3D("", dataset,true, true, false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
// 獲得圖表物件
PiePlot pie = (PiePlot) chart.getPlot();
// 設定圖的背景顏色
pie.setBackgroundPaint(Color.white);
//沒有資料時
pie.setNoDataMessage("沒有資料!");
// 圖片中顯示百分比:預設方式
// plot.setLabelGenerator(new
// StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 圖片中顯示百分比:自定義方式,{0} 表示選項, {1} 表示數值, {2} 表示所佔比例 ,小數點後兩位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({2})",
NumberFormat.getNumberInstance(), new DecimalFormat("0.0%")));
// 圖例顯示百分比:自定義方式, {0} 表示選項, {1} 表示數值, {2} 表示所佔比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(""));
// 設定背景色為白色
chart.setBackgroundPaint(Color.white);
// 指定圖片的透明度(0.0-1.0)
plot.setForegroundAlpha(1.0f);
// 指定顯示的餅圖上圓形(false)還橢圓形(true)
plot.setCircular(true);
// 設定圖示題的字型
Font font = new Font("黑體", Font.CENTER_BASELINE, 20);
TextTitle title = new TextTitle("");
title.setFont(font);
chart.setTitle(title);
plot.setLabelFont(new Font("SimSun", 0, 15));//裡面的字
LegendTitle legend = chart.getLegend(0);
legend.setItemFont(new Font("宋體", Font.BOLD,20));//下面的字
String path = new Property(Constant.propFilePath).getValue("reportUploadPath");//E:/temp/reppic/
File file = new File(path + "/" + filename);
try {
ChartUtilities.saveChartAsJPEG(
file,
1, // JPEG圖片的質量,0~1之間
chart, // 統計圖示物件
600, // 寬
}</span>