Skip to content

Instantly share code, notes, and snippets.

@alastairtree
Created December 7, 2015 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastairtree/ac4c0f111e5c647fb0fd to your computer and use it in GitHub Desktop.
Save alastairtree/ac4c0f111e5c647fb0fd to your computer and use it in GitHub Desktop.
Export items to an excel spreadsheet
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;
}
}
}
@alastairtree
Copy link
Author

Sample usage in a controller

    // GET: /Items/Export
    public ActionResult Export()
    {
        var items= GetAllItems();
        var excel = ExcelExportTool.GetReport("Items", items);
        var fileName = string.Format("Items_report_{0}.xlsx", DateTime.Now.ToString("dd-MMM-yy-HHmm"));
        return File(excel, ExcelExportTool.ContentType, fileName);
    }

@alastairtree
Copy link
Author

Note: requires lib from nuget Install-Package EPPlus, see http://epplus.codeplex.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment