Wpf Reportviewer 生成報表、柱狀圖

主要後臺邏輯:

using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace firstWpf
{
    /// <summary>
    /// Window1.xaml 的交互邏輯
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

//生成報表

        private void ReportViewer_Load()
        {
            Microsoft.Reporting.WinForms.ReportDataSource reportDataSource1 = new Microsoft.Reporting.WinForms.ReportDataSource();
            this.reportViewer2.LocalReport.DataSources.Clear();
            firstWpfDataSet dataset = new firstWpfDataSet();
            string txt = this.datepicker1.Text;
            //查詢數據庫
            DataTable dt_data = ConnectionSQLServerFunc();
            //var li=(from a in dt_data.AsEnumerable()
            //       group a by a.Field<DateTime>("time") into g
            //       // where g.Count() > 1
            //       select new
            //       {
            //           ph_avg = g.Average(x => x.Field<double>("PH")),
            //           bp_avg = g.Average(x => x.Field<double>("BP")),
            //           ap_avg = g.Average(x => x.Field<double>("AP")),
            //           time = g.Key
            //       }).ToList();

            List<area_rdlc> list = DataTableToList<area_rdlc>(dt_data);
            List<area_rdlc> all_list = new List<area_rdlc>() { };
            //計算日期
            List<string> timeArr= CalTime(txt);
            //組裝數據
            for (int i = 0; i < timeArr.Count(); i++)
            {
                all_list.Add(new area_rdlc
                {
                    ID = i,
                    PH = 0,
                    BP = 0,
                    AP=0,
                    time=DateTime.Parse(timeArr[i])
                });
            }
            //最終數據
            var result = (from a in list
                          group a by a.time into g
                         // where g.Count() > 1
                          select new {
                              ph_avg= g.Average(x => x.PH),
                              bp_avg= g.Average(x => x.BP),
                              ap_avg= g.Average(x => x.AP),
                              time=g.Key
                          } ).ToList();
            for (int i = 0; i < result.Count; i++)
            {
                for (int j = 0; j < all_list.Count; j++)
                {
                    if (result[i].time.Equals(all_list[j].time))
                    {

                        all_list[j].PH = result[i].ph_avg;
                        all_list[j].BP = result[i].bp_avg;
                        all_list[j].AP = result[i].ap_avg;
                    }
                }
            }
            //綁定數據
            dataset.BeginInit();
            reportDataSource1.Name = "DataSet1"; 
            reportDataSource1.Value = all_list;
            this.reportViewer2.LocalReport.DataSources.Add(reportDataSource1);
            this.reportViewer2.LocalReport.ReportEmbeddedResource = "firstWpf.Report2.rdlc";

            dataset.EndInit();

            //傳遞參數
            ReportParameter[] rp = new ReportParameter[1];
            rp[0]=new ReportParameter("time", txt);
            this.reportViewer2.LocalReport.SetParameters(rp);
            reportViewer2.ShowParameterPrompts = false;
           

            reportViewer2.RefreshReport();

        }
        //根據年月獲取所有日期
        public List<string> CalTime(string txt) {
           DateTime beginTime=DateTime.Parse(txt+"-01");//本月初
           DateTime endTime=DateTime.Parse( beginTime.AddMonths(1).AddDays(-1).ToShortDateString());//本月最後一天
            List<string> de = new List<string>();
            for (DateTime dt = beginTime; dt <= endTime; dt = dt.AddDays(1))
            {
                de.Add(dt.ToShortDateString());
            }
            return de;
        }

        //取數據庫數據
        public DataTable ConnectionSQLServerFunc()
        {
            //連接數據庫字符串
            string strConn = "Data Source=.;Initial Catalog=firstWpf;User ID=sa;Password=123456";
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                try
                {
                    string time = this.datepicker1.Text;
                    string[] timeStr = time.Split('-');
                    //連接數據庫
                    conn.Open();
                    //查詢數據庫語句
                    string commandStr = string.Format("select * from Area_Rdlc where Year(time)='{0}' AND Month(time)='{1}'", timeStr[0], timeStr[1]);
                    //要對數據源執行的 SQL 語句或存儲過程
                    SqlCommand sqlCmd = new SqlCommand(commandStr, conn);
                    //表示一組數據命令和一個數據庫連接,它們用於填充 System.Data.DataSet 和更新數據源。
                    SqlDataAdapter sqlDataAda = new SqlDataAdapter(sqlCmd);
                    //數據的內存中緩存
                    //將獲取到的數據填充到數據緩存中
                    sqlDataAda.Fill(dt);
                }
                catch (Exception ex)
                {

                }
            }
            return dt;
        }
        /// <summary> 
        /// 利用反射將DataTable轉換爲List<T>對象
        /// </summary> 
        /// <param name="dt">DataTable 對象</param> 
        /// <returns>List<T>集合</returns> 
        public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
        {
            // 定義集合 
            List<T> ts = new List<T>();
            //定義一個臨時變量 
            string tempName = string.Empty;
            //遍歷DataTable中所有的數據行 
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 獲得此模型的公共屬性 
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍歷該對象的所有屬性 
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;//將屬性名稱賦值給臨時變量 
                                       //檢查DataTable是否包含此列(列名==對象的屬性名)  
                    if (dt.Columns.Contains(tempName))
                    {
                        //取值 
                        object value = dr[tempName];
                        //如果非空,則賦給對象的屬性 
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                //對象添加到泛型集合中 
                ts.Add(t);
            }
            return ts;
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {

//查詢並生成報表
            ReportViewer_Load();
        }
    }
}
 

 

頁面截圖:

 

 

 

源碼下載:https://download.csdn.net/download/qq_34017733/11141215

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章