Controller - Open HomeController.cs - Add the action name( Articles_Export_ToExcel) which we have provided for Export to Excel in the View
-> 9 steps which I have mentioned in beginning of the article has been coded down in this function.
-> Add the below 2 using statements
using NPOI.HSSF.UserModel;//For using NPOI dll
using System.IO;//For memory stream //Export to Excel Action
public ActionResult Articles_Export_ToExcel(int page, string orderBy,string filter)
{
var tempArticles = objRepository.MyArticles_DisplayRecords();
//Create new Excel Workbook
var workbook =new HSSFWorkbook();
//Create new Excel Sheet
var sheet = workbook.CreateSheet();
//(Optional) set the width of the columns
sheet.SetColumnWidth(0, 20 * 256);//Title
sheet.SetColumnWidth(1, 20 * 256);//Section
sheet.SetColumnWidth(2, 20 * 256);//Views
sheet.SetColumnWidth(3, 20 * 256);//Downloads
sheet.SetColumnWidth(4, 20 * 256);//Status
//Create a header row
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Title");
headerRow.CreateCell(1).SetCellValue("Section");
headerRow.CreateCell(2).SetCellValue("Views");
headerRow.CreateCell(3).SetCellValue("Downloads");
headerRow.CreateCell(4).SetCellValue("Status");
//(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 (IndexTelerikGridViewModel objArticles in tempArticles)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber++);
//Set the Values for Cells
row.CreateCell(0).SetCellValue(objArticles.sTitle);
row.CreateCell(1).SetCellValue(objArticles.sSection);
row.CreateCell(2).SetCellValue(objArticles.iViews);
row.CreateCell(3).SetCellValue(objArticles.iDownloads);
row.CreateCell(4).SetCellValue(objArticles.sStatus);
}
//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
"ArticleList.xls"); //Suggested file name in the "Save as" dialog which will be displayed to the end user
}
![ExpExl1.gif]()