Export To Excel Data By LINQ to SQL

There are many times we require certain reports to be exported to certain require Files i.e Export to Excel, PDF and CSV but for today we can see how we can export to excel with querying to database through LINQ to SQL query.

So let's start to build interface buttons which will do the rest of work to query and export to excel.


  1. <asp:Button ID="btnGetData" runat="server" Text="Export to Excel" OnClick="btnGetData_Click" />  
This button has OnClick (btnGetData_Click) Event which will fire when we click on it, before starting we will add the following references to the project. on the upper section where reference are defined and also by adding in the Reference folder of solution.
  1. using System.Web;  
  2. using System.Drawing;  
  3. using System.Reflection;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using OfficeOpenXml;  
  7. using OfficeOpenXml.Style;  
  8. using OfficeOpenXml.Table;   
Now we will write the backend logic of button.
  1. protected void btnGetData_Click(object sender, EventArgs e)  
  2. {  
  3.   
  4. DataTable dt = new DataTable();  
  5. List<NewsFeed> NewsFeeds = (from emp in db.NewsFeed select emp).ToList<NewsFeed>();  
  6.             if (NewsFeeds.Any())  
  7. {  
  8. ListtoDataTableConverter converter = new ListtoDataTableConverter();  
  9. dt = converter.ToDataTable(NewsFeeds);  
  10.                 ExportExcel(dt);  
  11. }  
  12.   
  13. }  
Now I will explain the line of code as you can see we have a button event which will fire on click.
FIrst of all we create DataTable and initialize it on the start which will hold the converted data.
  1. DataTable dt = new DataTable();   
Now we have write the linq to sql query and all the result which will fetch through query is moved to the list.
  1. List<NewsFeed> NewsFeeds = (from emp in db.NewsFeed select emp).ToList<NewsFeed>();   
After that we will check as a best practice, is there any data returned by the query by writing line of code like this
  1. if (NewsFeeds.Any())  
  2. {  
  3.   
  4. }  
If list variable contains any thing we have use .Any() as a best practice to check the content length otherwise you can use .Count() method too to check for any count of returned row to do the rest of processing.
  1. if (NewsFeeds.Count())  
  2. {  
  3.   
  4. }   
Now we will create new class and initialize it to convert the list structure to datatable to ease our work as per our requirement.
  1. ListtoDataTableConverter converter = new ListtoDataTableConverter();   
Complete class is elaborated below.
  1. public class ListtoDataTableConverter  
  2.  {  
  3.  public DataTable ToDataTable<T>(List<T> items)  
  4. {  
  5.  DataTable dataTable = new DataTable(typeof(T).Name);  
  6. //Get all the properties  
  7.  PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  8.  // Loop through all the properties  
  9.  foreach (PropertyInfo prop in Props)  
  10.  {  
  11.  //Setting column names as Property names  
  12.  dataTable.Columns.Add(prop.Name);  
  13.  }  
  14.  
  15.  foreach (T item in items)  
  16. {  
  17.  var values = new object[Props.Length];  
  18.  for (int i = 0; i < Props.Length; i++)  
  19.  {  
  20.  //inserting property values to datatable rows  
  21.  values[i] = Props[i].GetValue(item, null);  
  22.  }  
  23.  // Finally add value to datatable  
  24.  dataTable.Rows.Add(values);  
  25.   
  26.  }  
  27.  //put a breakpoint here and check datatable of return values  
  28.  return dataTable;  
  29.  }  
  30. }  
I have elaborate every piece of code with comments what is going on while converting list to dataTable. We are using the DataTable method to convert it to the datatable from list inside class ListtoDataTableConverter.
  1. dt = converter.ToDataTable(NewsFeeds);   
Finally, we will use the Export to Excel function by allocating the content type to convert it to the appropriate format. We will call export method and pass converted dataTable from list.
  1. ExportExcel(dt);   
For conversion to excel purpose I am using microsoft built in library called open office XML Extension.

Right click on References folder of project and select Add Reference.

Add below highlighted Extensions in to the project.


Add This Method to File.
  1.  private void ExportExcel(DataTable dt)  
  2.    using (ExcelPackage pck = new ExcelPackage())  
  3.   {  
  4.   // Excel Sheet name  
  5.   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("ExportReport");  
  6.   // pass the cell from where we start dumping data and load the data from datatable  
  7.  ws.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium15);  
  8.   
  9.  //Read the Excel file in a byte array  
  10.  Byte[] fileBytes = pck.GetAsByteArray();  
  11.  HttpContext.Current.Response.ClearContent();  
  12.  // Add the content disposition (file name to be customizable) to be exported.  
  13.  HttpContext.Current.Response.AddHeader("content- disposition","attachment;filename=Exported_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xlsx");  
  14.   
  15.  // add the required content type  
  16.  HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
  17.  // write the bytes to the file and end the response  
  18.  HttpContext.Current.Response.BinaryWrite(fileBytes);  
  19.  HttpContext.Current.Response.End();  
  20.  
  21.  }  
  22.    
Code Elaboration:
  1.  // Excel Sheet name  
  2.   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("ExportReport");  
  3.   // pass the cell from where we start dumping data and load the data from datatable, also you can add styling by using table style and check name from excel file for required design  
  4.  
  5.   ws.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium15);  
  6.   //Read the Excel file in a byte array  
  7.   Byte[] fileBytes = pck.GetAsByteArray();  
  8.   
  9.  // Add the content disposition (file name to be customizable) to be exported.  
  10.  HttpContext.Current.Response.AddHeader("content-disposition""attachment;filename=Exported_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xlsx");  
  11.   
  12.  // add the required content type  
  13.  HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
  14.  // write the bytes to the file and end the response  
  15.  HttpContext.Current.Response.BinaryWrite(fileBytes);  
  16.  HttpContext.Current.Response.End();  
  17.   
Final Output

Read more articles on LINQ: