技术开发 频道

从Linq Queries快速生成数据报表详解

  【IT168技术】在CodePlex 上经常可以发现一些好东西, 关键是有没有时间去淘宝.前几天就发现一个, 并且在实际工作中使用了:* DoddleReport.

  你有没有被要求基于来自数据库的数据,生成一个报表? 我们时不时会有类似的需求.

  DoddleReport极大的简化了这方面的工作量.

  首先你需要下载它的Dll 文件, 可以到 codeplex 中得到http://doddlereport.codeplex.com/。得到的是一样的文件, 将它解压到你的一个asp.net 网站的bin目录下. 你就可以引用Doddle的类了.

  我们来模拟一个场景(本场景是根据DoddleReport提供的sample 代码改编的):

  创建一个aspx页面, 加入下面的代码:

  创建一个Product 类:

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; }
}

  随机生成1000个Product的数据, 方便我们测试结果:

public static List<Product> GetAll()
{
    var rand
= new Random();
    
return Enumerable.Range(1, 1000)
        .Select(i
=> new Product
        {
            Id
= i,
            Name
= "产品 " + i,
            Description
=
                "描述...",
            Price
= rand.NextDouble() * 100,
            OrderCount
= rand.Next(1000),
            LastPurchase
= DateTime.Now.AddDays(rand.Next(1000)),
            UnitsInStock
= rand.Next(0, 2000)
        })
        .ToList();
}

   下面我们要用到DoddleReport的类:

protected void Page_Load(object sender, EventArgs e)
{
// Get the data for the report (any IEnumerable will work)
var query
= GetAll();

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

// Customize the Text Fields
report.TextFields.Title
= "报告的标题";
report.TextFields.SubTitle
= "副标题";
report.TextFields.Footer
= "页脚";
report.TextFields.Header
= string.Format(@"制作时间: {0}", DateTime.Now);

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


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

var writer
= new HtmlReportWriter();
writer.WriteReport(report, Response.OutputStream);
}

  首先用我们的数据生成一个Report的实例; 然后指定Report的一些属性, 例如标题, 页眉, 页脚(很酷,是吗). 再指定一些列的属性, 例如隐藏ID, 和给一些列特殊的格式.

  最后调用ReportWriter将数据写出到页面.

  下面是生成的截图:

  如果你要生成Excel 或者CSV(以逗号或者tab为分隔符的文件)可以简单的修改ReportWriter后面的代码为:

string s = Request.PhysicalApplicationPath;
var exWriter
= new ExcelReportWriter();
exWriter.WriteReport(report, System.IO.File.Create(s
+ "fil7.xls"));

   或者

var deWriter = new DelimitedTextReportWriter();
deWriter.WriteReport(report, System.IO.File.Create(s
+ "fil7.csv"));

   可以看看效果:

0
相关文章