[HttpGet]
public ViewResult Index()
{
return View(CreateExportableGrid());
}
[HttpGet]
public ViewResult ExportIndex()
{
// Using EPPlus from nuget
using (ExcelPackage package = new ExcelPackage())
{
Int32 row = 2;
Int32 col = 1;
package.Workbook.Worksheets.Add("Data");
IGrid<Person> grid = CreateExportableGrid();
ExcelWorksheet sheet = package.Workbook.Worksheets["Data"];
foreach (IGridColumn column in grid.Columns)
{
sheet.Cells[1, col].Value = column.Title;
sheet.Column(col++).Width = 18;
column.IsEncoded = false;
}
foreach (IGridRow<Person> gridRow in grid.Rows)
{
col = 1;
foreach (IGridColumn column in grid.Columns)
sheet.Cells[row, col++].Value = column.ValueFor(gridRow);
row++;
}
return File(package.GetAsByteArray(), "application/unknown", "Export.xlsx");
}
}
private IGrid<Person> CreateExportableGrid()
{
IGrid<Person> grid = new Grid<Person>(repository.GetPeople());
grid.ViewContext = new ViewContext { 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");
grid.Pager = new GridPager<Person>(grid);
grid.Processors.Add(grid.Pager);
grid.Pager.RowsPerPage = 6;
foreach (IGridColumn column in grid.Columns)
{
column.Filter.IsEnabled = true;
column.Sort.IsEnabled = true;
}
return grid;
}