[HttpGet]
public ViewResult Index()
{
return View(CreateExportableGrid());
}
[HttpGet]
public ViewResult ExportIndex()
{
return Export(CreateExportableGrid(), "People");
}
// Using EPPlus from nuget.
// Export grid method can be reused for all grids.
private FileContentResult Export(IGrid grid, String fileName)
{
Int32 col = 1;
using ExcelPackage package = new ExcelPackage();
ExcelWorksheet sheet = package.Workbook.Worksheets.Add("Data");
foreach (IGridColumn column in grid.Columns)
{
sheet.Cells[1, col].Value = column.Title;
sheet.Column(col++).Width = 18;
column.IsEncoded = false;
}
foreach (IGridRow<Object> row in grid.Rows)
{
col = 1;
foreach (IGridColumn column in grid.Columns)
sheet.Cells[row.Index + 2, col++].Value = column.ValueFor(row);
}
return File(package.GetAsByteArray(), "application/unknown", $"{fileName}.xlsx");
}
private IGrid<Person> CreateExportableGrid()
{
IGrid<Person> grid = new Grid<Person>(repository.GetPeople());
grid.HttpContext = HttpContext;
grid.Query = Request.Query;
grid.Columns.Add(model => model.Name).Titled("Name");
grid.Columns.Add(model => model.Surname).Titled("Surname");
grid.Columns.Add(model => model.Age).Titled("Age");
grid.Columns.Add(model => model.Birthday).Titled("Birthday").Formatted("{0:d}");
grid.Columns.Add(model => model.IsWorking).Titled("Employed");
// Pager should be excluded on export if all data is needed.
grid.Pager = new GridPager<Person>(grid);
grid.Processors.Add(grid.Pager);
grid.Processors.Add(grid.Sort);
grid.Pager.RowsPerPage = 6;
foreach (IGridColumn column in grid.Columns)
{
column.Filter.IsEnabled = true;
column.Sort.IsEnabled = true;
}
return grid;
}