Created
December 7, 2015 11:34
-
-
Save alastairtree/ac4c0f111e5c647fb0fd to your computer and use it in GitHub Desktop.
Export items to an excel spreadsheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Reflection; | |
using OfficeOpenXml; | |
using OfficeOpenXml.Table; | |
namespace Utils | |
{ | |
public static class ExcelExportTool | |
{ | |
public static readonly string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; | |
public static byte[] GetReport<T>(string worksheetName, IEnumerable<T> items) | |
{ | |
var table = ToDataTable(items); | |
using (var package = new ExcelPackage()) | |
{ | |
var worksheet = package.Workbook.Worksheets.Add(worksheetName); | |
worksheet.Cells.LoadFromDataTable(table, true, TableStyles.Light8); | |
return package.GetAsByteArray(); | |
} | |
} | |
private static DataTable ToDataTable<T>(IEnumerable<T> entityList) | |
{ | |
var dtReturn = new DataTable(); | |
// column names | |
PropertyInfo[] oProps = null; | |
if (entityList == null) return dtReturn; | |
foreach (var rec in entityList) | |
{ | |
// Use reflection to get property names, to create table, Only first time, others will follow | |
if (oProps == null) | |
{ | |
oProps = rec.GetType().GetProperties(); | |
foreach (var pi in oProps) | |
{ | |
var colType = pi.PropertyType; | |
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof (Nullable<>))) | |
{ | |
colType = colType.GetGenericArguments()[0]; | |
} | |
dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); | |
} | |
} | |
var dr = dtReturn.NewRow(); | |
foreach (var pi in oProps) | |
{ | |
dr[pi.Name] = pi.GetValue(rec, null) ?? DBNull.Value; | |
} | |
dtReturn.Rows.Add(dr); | |
} | |
return dtReturn; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage in a controller