如何为您的 LINQ 查询构建通用 EPPlus 电子表格函数?
更新:需要专门针对 ASP.NET MVC 应用程序。
我所做的只是创建一个接受列表的通用函数。我使用反射来获取属性列表,这将成为我们的列标题。最后,我只是让 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();
}
}
现在有一种更简单的方法可以使用 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();
}
}
示例取自这里: http: //gruffcode.com/2013/10/30/simple-excel-export-with-epplus/