随笔 - 838  文章 - 5 评论 - 949 trackbacks - 19

有的时候,我们需要对一堆数据进行统计分析后生成HTML或Excel格式报表。本来这并不是一件很难的事,但确是件比较麻烦的事情。最令人头痛的是遇到领导下发的临时紧急任务的时候,往往领导都不知道到底要什么报表,只是给你一堆数据先让你出一个分析报告,当你上缴分析报告后,领导会针对分析结果让你再出一个分析报告… 。这时要是有一个快速生成报表的工具就非常方便了。

现在,我们可以通过DoddleReport来快速生成报表。一个简单的示例如下:

假定我们的数据对象为如下格式:

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public int OrderCount { get; set; }
        public DateTime LastPurchase { get; set; }
        public int UnitsInStock { get; set; }
    }

数据源通如下函数生成:

    static IEnumerable<Product> GetAllData()
    {
        var rand = new Random();
        return Enumerable.Range(1, 20).Select(
            i => new Product
            {
                Id = i,
                Name = "Product " + i,
                Description = "This is an example description",
                Price = rand.NextDouble() * 100,
                OrderCount = rand.Next(1000),
                LastPurchase = DateTime.Now.AddDays(rand.Next(1000)),
                UnitsInStock = rand.Next(0, 2000)
            });
    }

要对该数据源生成报表,则只需要如下几步:


1. 通过ToReportSource扩展函数将数据源转换为Report对象


    // Create the report and turn our query into a ReportSource
    var report = new Report(GetAllData().ToList().ToReportSource());

2. 添加报表的标题和页眉页脚的描述


    // Customize the Text Fields
    report.TextFields.Title = "Products Report";
    report.TextFields.SubTitle = "This is a sample report showing how Doddle Report works";
    report.TextFields.Footer = "Copyright 2011 &copy; The Doddle Project";
    report.TextFields.Header = string.Format(@" Report Header Demo");

    // Render hints allow you to pass additional hints to the reports as they are being rendered
    report.RenderHints.BooleanCheckboxes = true;


3. 对输出的字段进行格式控制


    // Customize the data fields
    report.DataFields["Id"].Hidden = true;
    report.DataFields["Price"].DataFormatString = "{0:c}";
    report.DataFields["LastPurchase"].DataFormatString = "{0:d}";


4. 输出为报表


    using (var outputStream = File.Create(@"r:\report.html"))
    {
        var writer = new DoddleReport.Writers.HtmlReportWriter();
        writer.WriteReport(report, outputStream);
    }

这样,我们就可以得到如下的报表:

使用起来非常简单,但基本上该有的都有,还是非常不错的。其中2,3两步是可以省略的,最简单的方式下,只要如下几行即可:

    // Create the report and turn our query into a ReportSource
    var report = new Report(GetAllData().ToList().ToReportSource());

    using (var outputStream = File.Create(@"r:\report.html"))
    {
        var writer = new DoddleReport.Writers.HtmlReportWriter();
        writer.WriteReport(report, outputStream);
    }

值得一提的是,DoddleReport支持的输出给事非常丰富:PDF、EXCEL、HTML、CSV等常用的格式都支持,也能直接在Asp.net中输出成在线报表。例如,我们只要把上面例子中的"Writers.HtmlReportWriter"改成"OpenXml.ExcelReportWriter"就可以生成Excel格式的报表,非常强大而方便。

 

posted on 2013-06-09 23:49  天方  阅读(...)  评论(...编辑  收藏