Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KendoGridAdminController : Controller
- {
- public virtual IEnumerable GetData()
- {
- return null;
- }
- [HttpGet]
- public FileResult ExportToExcel([DataSourceRequest]DataSourceRequest request)
- {
- var data = GetData();
- Type dataType = data.GetType().GetGenericArguments()[0];
- var dataTypeProperties = dataType.GetProperties();
- if (data == null || dataType == null)
- {
- throw new Exception("GetData() and DataType must be overriden");
- }
- //Get the data representing the current grid state - page, sort and filter
- IEnumerable items = data.ToDataSourceResult(request).Data;
- //Create new Excel workbook
- var workbook = new HSSFWorkbook();
- //Create new Excel sheet
- var sheet = workbook.CreateSheet();
- // Create a header row
- var headerRow = sheet.CreateRow(0);
- int columnNumber = 0;
- foreach (var property in dataTypeProperties)
- {
- string cellName = property.Name;
- object[] attributes = property.GetCustomAttributes(typeof(DisplayAttribute), true);
- if (attributes != null && attributes.Count() > 0)
- {
- DisplayAttribute attribute = attributes[0] as DisplayAttribute;
- cellName = attribute.Name ?? property.Name;
- }
- headerRow.CreateCell(columnNumber++).SetCellValue(cellName);
- }
- //(Optional) freeze the header row so it is not scrolled
- sheet.CreateFreezePane(0, 1, 0, 1);
- int rowNumber = 1;
- //Populate the sheet with values from the grid data
- foreach (object item in items)
- {
- //Create a new row
- var row = sheet.CreateRow(rowNumber++);
- int cellNumber = 0;
- foreach (var property in dataTypeProperties)
- {
- object propertyValue = item.GetType().GetProperty(property.Name).GetValue(item, null);
- if (propertyValue == null)
- {
- row.CreateCell(cellNumber++).SetCellType(NPOI.SS.UserModel.CellType.BLANK);
- }
- else
- {
- row.CreateCell(cellNumber++).SetCellValue(propertyValue.ToString());
- }
- }
- }
- // Autosize all columns
- for (int i = 0; i < columnNumber; i++)
- {
- sheet.AutoSizeColumn(i);
- }
- //Write the workbook to a memory stream
- MemoryStream output = new MemoryStream();
- workbook.Write(output);
- //Return the result to the end user
- return File(output.ToArray(), //The binary data of the XLS file
- "application/vnd.ms-excel", //MIME type of Excel files
- "GridExcelExport.xls"); //Suggested file name in the "Save as" dialog which will be displayed to the end user
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement