从 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; }
}
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();
}
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, 和给一些列特殊的格式.
如果你要生成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) 转贴请注明出处
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库