从 Linq Queries 快速生成数据 HTML, EXCEL, CSV 报表
在CodePlex 上经常可以发现一些好东西, 关键是有没有时间去淘宝.
前几天就发现一个, 并且在实际工作中使用了:
* DoddleReport你有没有被要求基于来自数据库的数据,生成一个报表? 我们时不时会有类似的需求.
DoddleReport极大的简化了这方面的工作量.
首先你需要下载它的Dll 文件, 可以到 codeplex 中得到 http://doddlereport.codeplex.com/
或者直接从这里下载: cnblogs下载地址
得到的是一样的文件, 将它解压到你的一个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"));
可以看看效果:
希望可以帮助到有这方面需要的朋友们.
本文来自于 喜乐的ASP.NET(Alex Song) 转贴请注明出处
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于从 Linq Queries 快速生成数据 HTML, EXCEL, CSV 报表的详细内容...