從 Linq Queries 快速生成數(shù)據(jù) HTML, EXCEL, CSV 報(bào)表
在CodePlex 上經(jīng)??梢园l(fā)現(xiàn)一些好東西, 關(guān)鍵是有沒有時(shí)間去淘寶.
前幾天就發(fā)現(xiàn)一個(gè), 并且在實(shí)際工作中使用了:
* DoddleReport
你有沒有被要求基于來自數(shù)據(jù)庫的數(shù)據(jù),生成一個(gè)報(bào)表? 我們時(shí)不時(shí)會有類似的需求.
DoddleReport極大的簡化了這方面的工作量.
首先你需要下載它的Dll 文件, 可以到 codeplex 中得到http://doddlereport.codeplex.com/
或者直接從這里下載: cnblogs下載地址
得到的是一樣的文件, 將它解壓到你的一個(gè)asp.net 網(wǎng)站的bin目錄下. 你就可以引用Doddle的類了.
我們來模擬一個(gè)場景(本場景是根據(jù)DoddleReport提供的sample 代碼改編的):
創(chuàng)建一個(gè)aspx頁面, 加入下面的代碼:
創(chuàng)建一個(gè)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 = "產(chǎn)品 " + 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 = "報(bào)告的標(biāo)題";
report.TextFields.SubTitle = "副標(biāo)題";
report.TextFields.Footer = "頁腳";
report.TextFields.Header = string.Format(@"制作時(shí)間: {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);
}
首先用我們的數(shù)據(jù)生成一個(gè)Report的實(shí)例; 然后指定Report的一些屬性, 例如標(biāo)題, 頁眉, 頁腳(很酷,是嗎). 再指定一些列的屬性, 例如隱藏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) 轉(zhuǎn)貼請注明出處




浙公網(wǎng)安備 33010602011771號