• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#报表柱,饼状图

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Security.Permissions;
using System.Web;
using System.Web.Hosting;

namespace AIMS.Web.Helper
{
    /// <summary>
    /// 报表助手
    /// </summary>
    public class ReportHelper
    {
        private LocalReport report = new LocalReport();

        public string OutUrl { get; set; } = "~/Reports/Exports";

        public ReportHelper(string reportPath)
        {
            report.ReportPath = reportPath;
            report.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));
        }

        public void SetParameters(IEnumerable<ReportParameter> parameters)
        {
            report.SetParameters(parameters);
        }

        public void LoadDataSource(List<ReportDataSource> dataSources)
        {
            foreach (var dataSource in dataSources)
            {
                report.DataSources.Add(dataSource);
            }
        }

        public void LoadDataSource(Dictionary<string, Object> dataSources)
        {
            foreach (var dataSource in dataSources)
            {
                report.DataSources.Add(new ReportDataSource(dataSource.Key, dataSource.Value));
            }
        }

        /// <summary>
        /// 用新数据呈现
        /// </summary>
        public void Refresh()
        {
            report.Refresh();
        }

        /// <summary>
        /// 导出为字节数组
        /// </summary>
        /// <param name="format">[PDF|Word|Excel|Image]</param>
        /// <param name="extension">输出扩展名</param>
        /// <returns>字节数组</returns>
        public byte[] ExportToBuffer(string format, out string extension)
        {
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            byte[] buffer = report.Render(
               format, null, out mimeType, out encoding, out extension,
               out streamids, out warnings);

            return buffer;
        }

        /// <summary>
        /// 导出到输出流
        /// </summary>
        /// <param name="format">[PDF|Word|Excel|Image]</param>
        /// <param name="writeStream">输出流</param>
        /// <returns>扩展名</returns>
        public string ExportToStream(string format, Stream writeStream)
        {
            string extension;
            byte[] buffer = ExportToBuffer(format, out extension);
            writeStream.Write(buffer, 0, buffer.Length);
            return extension;
        }

        /// <summary>
        /// 导出到文件
        /// </summary>
        /// <param name="format">[PDF|Word|Excel|Image]</param>
        /// <param name="fileName">文件名(不需要扩展名)</param>
        /// <returns>文件名(包含扩展名)</returns>
        public string ExportToFile(string format, string fileName = "export")
        {
            string directory = HostingEnvironment.MapPath(this.OutUrl);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string extension;
            byte[] buffer = ExportToBuffer(format, out extension);
            string fileFullName = fileName + "." + extension;
            string filePath = Path.Combine(directory, fileFullName);
            FileStream fs = new FileStream(filePath, FileMode.Create);
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();
            return fileFullName;
        }


        /// <summary>
        /// 打印报表(生成PDF文件,返回PDF文件URL)
        /// </summary>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>URL(生成PDF文件的URL)</returns>
        public static string Print(string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            ReportHelper helper = new ReportHelper(reportPath);
            if (parameters != null) helper.SetParameters(parameters);
            helper.LoadDataSource(dataSources);
            helper.Refresh();
            string fileName = helper.ExportToFile("PDF", "print");
            return helper.OutUrl.TrimEnd('/') + "/" + fileName;
        }
        /// <summary>
        /// 导出到文件
        /// </summary>
        /// <param name="format">[PDF|Word|Excel|Image]</param>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>文件物理路径</returns>
        public static string ExportToFile(string format, string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            ReportHelper helper = new ReportHelper(reportPath);
            if (parameters != null) helper.SetParameters(parameters);
            helper.LoadDataSource(dataSources);
            helper.Refresh();
            string fileName = helper.ExportToFile(format);
            string fileUrl = helper.OutUrl.TrimEnd('/') + "/" + fileName;
            return HostingEnvironment.MapPath(fileUrl);
        }
        /// <summary>
        /// 分格式导出数据流到前端
        /// </summary>
        /// <param name="format">[PDF|Word|Excel|Image]</param>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>Http响应信息</returns>
        public static HttpResponseMessage Export(string format, string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            ReportHelper helper = new ReportHelper(reportPath);
            if (parameters != null) helper.SetParameters(parameters);
            helper.LoadDataSource(dataSources);
            helper.Refresh();
            string extension;
            byte[] buffer = helper.ExportToBuffer(format, out extension);
            string saveFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + extension;

            try
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(buffer);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = saveFileName
                };
                return response;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }
        /// <summary>
        /// 导出Excel格式数据流到前端
        /// </summary>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>Http响应信息</returns>
        public static HttpResponseMessage ExportExcel(string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            return Export("Excel", reportPath, dataSources, parameters);
        }
        /// <summary>
        /// 导出Word格式数据流到前端
        /// </summary>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>Http响应信息</returns>
        public static HttpResponseMessage ExportWord(string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            return Export("Word", reportPath, dataSources, parameters);
        }
        /// <summary>
        /// 导出PDF格式数据流到前端
        /// </summary>
        /// <param name="reportPath">报表文件路径</param>
        /// <param name="dataSources">数据源集合</param>
        /// <param name="parameters">参数集合</param>
        /// <returns>Http响应信息</returns>
        public static HttpResponseMessage ExportPDF(string reportPath, Dictionary<string, Object> dataSources, IEnumerable<ReportParameter> parameters = null)
        {
            return Export("PDF", reportPath, dataSources, parameters);
        }
    }
}

 

 

 

using AIMS.Bussiness.ApplicationDto.NJWorkTasks;
using AIMS.Bussiness.ApplicationDto.NJWorkTasksDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace AIMS.Bussiness.Application.Application.WorkTasksDetailsApp
{
  public  interface IWorkTasksDetailsAppService
    {
        List<WorkTasksDetailsModel> GetWorkTasksDetailsList(Guid orgId, DateTime startDate, DateTime endDate);
        
        WorkTasksReportResult GetWorkTasksReportResult(Guid orgId, DateTime startDate, DateTime endDate);

        WorkTasksReportResult GetWorkTasksReportResult(Guid orgId, DateTime startDate, DateTime endDate, int rows, int page);

    }
}
using AIMS.Bussiness.ApplicationDto.NJWorkTasks;
using AIMS.Model;
using Common.BaseLibrary.Unity;
using Common.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AIMS.Bussiness.ApplicationDto.NJWorkTasksDto;
using AIMS.Bussiness.ApplicationDto.Dto;

using Microsoft.Practices.Unity;

using AIMS.Bussiness.ApplicationDto.Enum;
using AIMS.Bussiness.Application.Application.WorkDefaultConfigApp;
using System.Net.Http;
using System.IO;

namespace AIMS.Bussiness.Application.Application.WorkTasksDetailsApp
{
    public class WorkTasksDetailsAppService : IWorkTasksDetailsAppService
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        //public List<WorkTasksDetailsModel> GetWorkTasksDetailsList(Guid orgId, DateTime startDate, DateTime endDate)
        //{
        //    //WorkTasksDetailsModel model = new WorkTasksDetailsModel();

        //    IExtensionRepository<NJWorkTasks> NJWorkTasksService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJWorkTasks>>();
        //    IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();
        //    IExtensionRepository<User> userService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<User>>();
        //    IExtensionRepository<Operator> OperatorService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Operator>>();
        //    IExtensionRepository<OperationType> OperationTypeService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<OperationType>>();
        //    IExtensionRepository<NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJ>>();

        //    var NJWorkTasksQuery = NJWorkTasksService.GetModel(p => p.TaskStopTime != null && p.TaskStartTime != null && p.TaskStopTime >= startDate && p.TaskStopTime <= endDate && p.OrgId == orgId).AsEnumerable();
        //    var OperationTypeQuery = OperationTypeService.GetModel(p => p.IsDeleted != true).AsEnumerable();
        //    var NJQuery = NJService.GetModel(p => p.IsDeleted != true).AsEnumerable();

        //    //var orgList = orgService.GetModel().Where(p => p.IsDisabled != true).ToList();
        //    //var userList = userService.GetModel().Where(p => p.IsDeleted != true).ToList();

        //    //var query = from n in NJWorkTasksQuery
        //    //            join u in NJQuery on n.TaskNJID equals u.Id
        //    //            join o in OperationTypeQuery on n.TaskOperationTypeID equals o.TypeDef into jwo
        //    //            from o in jwo.DefaultIfEmpty()
        //    //            join s in userList on n.DriverId equals s.Id into jwd
        //    //            from s in jwd.DefaultIfEmpty()
        //    //            select new WorkTasksDetailsModel
        //    //            {
        //    //                TaskName = n.TaskName,
        //    //                OperationName = o != null ? o.OperationName : "",
        //    //                NJName = u.NJName,
        //    //                TaskStopTime = n.TaskStopTime,
        //    //                WorkingHours = Math.Round((n.TaskStopTime.Value - n.TaskStartTime.Value).TotalHours, 1),
        //    //                TaskOptAreaSum = n.TaskOptAreaSum,
        //    //                TaskLengthSum = n.TaskLengthSum,
        //    //                TaskOptPrice = n.TaskOptPrice,
        //    //                TaskAllowanceSum = n.TaskAllowanceSum,
        //    //                FarmerName = "",
        //    //                DriverName = s != null ? s.Name : "",
        //    //                OpinionRating = "5星",
        //    //                AuditSituation = "已审核",

        //    //            };

        //    return query.ToList();


        //}


        public WorkTasksReportResult GetWorkTasksReportResult(Guid orgId, DateTime startDate, DateTime endDate)
        {
            WorkTasksReportResult model = new WorkTasksReportResult();
            var list = GetWorkTasksDetailsList(orgId, startDate, endDate);
            model.percentofpass = 90;
            model.WorkTasksDetailsModels = list;
            model.TotalTaskAllowanceSum = 0;
            model.TotalTaskLengthSum = 0;
            model.TotalTaskNum = 0;
            model.TotalTaskOptAreaSum = 0;
            model.TotalTaskOptPrice = 0;
            model.TotalWorkingHours = 0;
            model.NJTypeStatsPie = new ChartPieDto();
            model.TimeSpanStatsBar = new ChartBarDto();

            //柱状图dto
            var dtSpan = endDate - startDate;
            bool isByDay = false;
            if (dtSpan.TotalHours > 24)
            {
                //按天统计
                isByDay = true;
                var date = startDate.Date;
                while (date <= endDate)
                {
                    model.TimeSpanStatsBar.XAxisData.Add(date.ToString("yyyy-MM-dd"));
                    model.TimeSpanStatsBar.SeriesData.Add(0);
                    date = date.AddDays(1);
                }
            }
            else
            {
                //按小时统计
                var date = startDate.Date.AddHours(startDate.Hour);
                while (date <= endDate)
                {
                    model.TimeSpanStatsBar.XAxisData.Add(date.ToString("HH:mm"));
                    model.TimeSpanStatsBar.SeriesData.Add(0);
                    date = date.AddHours(1);
                }
            }

            foreach (var item in list)
            {
                //model.TotalTaskAllowanceSum += item.TaskAllowanceSum ?? 0;
                model.TotalTaskLengthSum += item.TaskLengthSum ?? 0;
                model.TotalTaskNum += 1;
                model.TotalTaskOptAreaSum += item.TaskOptAreaSum ?? 0;
                //model.TotalTaskOptPrice += item.TaskOptPrice ?? 0;
                model.TotalWorkingHours += item.WorkingHours ?? 0;

                //饼图dto
                int index = model.NJTypeStatsPie.LegendData.IndexOf(item.NJTypeName);
                if (index < 0)
                {
                    model.NJTypeStatsPie.LegendData.Add(item.NJTypeName);
                    model.NJTypeStatsPie.SeriesData.Add(new ChartPieSeriesDataItem { name = item.NJTypeName, value = item.TaskOptAreaSum ?? 0 });
                }
                else
                {
                    model.NJTypeStatsPie.SeriesData[index].value += item.TaskOptAreaSum ?? 0;
                }

                //柱状图dto
                DateTime optDate = Convert.ToDateTime(item.OperationEnd);
                string xAxisDate = "";
                if (isByDay)
                {
                    xAxisDate = optDate.Date.ToString("yyyy-MM-dd");
                }
                else
                {
                    xAxisDate = optDate.Date.AddHours(optDate.Hour).ToString("HH:mm");
                }

                index = model.TimeSpanStatsBar.XAxisData.IndexOf(xAxisDate);
                if (index > 0)
                {
                    model.TimeSpanStatsBar.SeriesData[index] += item.TaskOptAreaSum ?? 0;
                }
                else
                {
                    //应该没有这种情况
                }

            }
            return model;
        }
        //===============================================================================================================================
        public WorkTasksReportResult GetWorkTasksReportResult(Guid orgId, DateTime startDate, DateTime endDate, int rows, int page)
        {
            var model = GetWorkTasksReportResult(orgId, startDate, endDate);
            IEnumerable<WorkTasksDetailsModel> WorkTasksDetailsList = model.WorkTasksDetailsModels;
            int startIndex = (page - 1) * rows;

            if (model.TotalTaskNum > rows && rows != -1)
            {
                if ((startIndex + rows) > model.TotalTaskNum)
                    WorkTasksDetailsList = WorkTasksDetailsList.Skip(startIndex).Take(model.TotalTaskNum - startIndex);
                else
                    WorkTasksDetailsList = WorkTasksDetailsList.Skip(startIndex).Take(rows);
            }
            model.WorkTasksDetailsModels = WorkTasksDetailsList.ToList();

            return model;
        }
        //==========================================================================================================================================



        //==========================================================Zoe======================================================================================


        public List<WorkTasksDetailsModel> GetWorkTasksDetailsList(Guid orgId, DateTime startDate, DateTime endDate)
        {
            //WorkTasksDetailsModel model = new WorkTasksDetailsModel();

            IExtensionRepository<NJWorkTasks> NJWorkTasksService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJWorkTasks>>();
            //IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();
            //IExtensionRepository<User> userService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<User>>();
            //IExtensionRepository<Operator> OperatorService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Operator>>();
            IExtensionRepository<OperationType> OperationTypeService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<OperationType>>();
            IExtensionRepository<NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJ>>();
            IExtensionRepository<NJType> NJTypeService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJType>>();

            var NJWorkTasksQuery = NJWorkTasksService.GetModel(p => p.TaskStartTime != null && p.OperationEnd >= startDate && p.OperationEnd <= endDate && p.OrgId == orgId).AsEnumerable();
            var OperationTypeQuery = OperationTypeService.GetModel(p => p.IsDeleted != true).AsEnumerable();
            var NJQuery = NJService.GetModel(p => p.IsDeleted != true).AsEnumerable();
            var NJTypeQuery = NJTypeService.GetModel().AsEnumerable();

            var query = from n in NJWorkTasksQuery
                        join u in NJQuery on n.TaskNJID equals u.Id
                        join o in OperationTypeQuery on n.TaskOperationTypeID equals o.TypeDef into jwo
                        from o in jwo.DefaultIfEmpty()
                        join t in NJTypeQuery on u.NJTypeID equals t.Id into jut
                        from t in jut.DefaultIfEmpty()
                        select new WorkTasksDetailsModel
                        {
                            TaskName = n.TaskName,
                            OperationName = o != null ? o.OperationName : "",
                            NJName = u.NJName,
                            OperationStart = n.OperationStart.ToString("yyyy-MM-dd HH:mm:ss"),
                            OperationEnd = n.OperationEnd.ToString("yyyy-MM-dd HH:mm:ss"),
                            WorkingHours = Math.Round((n.OperationEnd - n.OperationStart).TotalHours, 1),
                            TaskOptAreaSum = n.TaskOptAreaSum,
                            TaskLengthSum = n.TaskLengthSum,
                            NJTypeID = u.NJTypeID,
                            NJTypeName = t != null ? t.ItemsName : ""
                        };

            return query.ToList();


        }
        //====================================================================Zoe==============================================================================







    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using AIMS.Bussiness.Interface;
using AIMS.Web.Helper;
using AIMS.Bussiness.Application.Application.WorkTasksDetailsApp;
 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
在C#的数据类型中,什么属于值类型,什么属于引用类型发布时间:2022-07-18
下一篇:
C#扩展方法——去重(Distinct)发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap