Cap*_*chi 4 c# asp.net-mvc epplus
如何为LINQ查询构建通用的EPPlus Spreadsheet函数?
更新:需要专门用于ASP.NET MVC应用程序.
Cap*_*chi 20
我所做的就是创建一个接受List的通用函数.我使用反射来获取属性列表,这将成为我们的列标题.最后,我只是让EPPlus完成所有繁重的工作.
void ListToExcel<T>(List<T> query)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Result");
//get our column headings
var t = typeof(T);
var Headings = t.GetProperties();
for (int i = 0; i < Headings.Count(); i++)
{
ws.Cells[1, i+1].Value = Headings[i].Name;
}
//populate our Data
if (query.Count() > 0)
{
ws.Cells["A2"].LoadFromCollection(query);
}
//Format the header
using (ExcelRange rng = ws.Cells["A1:BZ1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
现在有一种更简单的方法可以使用 LoadFromCollection 方法来实现这一点。
public void ExportToExcel(IEnumerable<Employee> employees, FileInfo targetFile)
{
using (var excelFile = new ExcelPackage(targetFile))
{
var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].LoadFromCollection(Collection: employees, PrintHeaders: true);
excelFile.Save();
}
}
Run Code Online (Sandbox Code Playgroud)
示例取自此处:http : //gruffcode.com/2013/10/30/simple-excel-export-with-epplus/
| 归档时间: |
|
| 查看次数: |
9272 次 |
| 最近记录: |