Export Model List To Excel In C# (Using Interop) - The Easy Way!

There are many ways to generate Excel files in C# using a  third party library but I am going to show you how to export Excel files from your entity without using any third party, with the help of Interop.
 
For reference we are going to use Microsoft.Office.Interop.Excel package.

In this demo, I have created a C# console app and to separate Excel Export Operation I have created another class called excelexport.cs.
 
 
To work on,  I need a model class and a list of objects to that model. So I have created a Model folder and inside that folder I have created a class called UserManager.cs
  1. public class UserManager  
  2. {  
  3.     public string Id { getset; }  
  4.     public string Username { getset; }  
  5.     public string FirstName { getset; }  
  6.     public string LastName { getset; }  
  7.     public string Password { getset; }  
  8.     public DateTime CreatedOn { getset; }  
  9. }  
But I need to generate a list of objects for this class as I am not using any database for this. So I have created a seed method to generate a set of dummy datas. 
  1. public static List<UserManager> SeedData()  
  2. {  
  3.     return new List<UserManager>  
  4.     {  
  5.         new UserManager  
  6.         {  
  7.             Id = Guid.NewGuid().ToString(),  
  8.             FirstName = "Test 1",  
  9.             LastName = "Test 1",  
  10.             Username = "TestUsername1",  
  11.             Password = "123",  
  12.             CreatedOn = DateTime.UtcNow  
  13.         },  
  14.         new UserManager  
  15.         {  
  16.             Id = Guid.NewGuid().ToString(),  
  17.             FirstName = "Test 2",  
  18.             LastName = "Test 2",  
  19.             Username = "TestUsername2",  
  20.             Password = "123",  
  21.             CreatedOn = DateTime.UtcNow  
  22.         },  
  23.         new UserManager  
  24.         {  
  25.             Id = Guid.NewGuid().ToString(),  
  26.             FirstName = "Test 3",  
  27.             LastName = "Test 3",  
  28.             Username = "TestUsername3",  
  29.             Password = "123",  
  30.             CreatedOn = DateTime.UtcNow  
  31.         },new UserManager  
  32.         {  
  33.             Id = Guid.NewGuid().ToString(),  
  34.             FirstName = "Test 4",  
  35.             LastName = "Test 4",  
  36.             Username = "TestUsername4",  
  37.             Password = "123",  
  38.             CreatedOn = DateTime.UtcNow  
  39.         }  
  40.     };  
  41. }  
So for now my UserManager class looks like this.
 
 
Our data is ready and now we need to make our Datatable converter to convert our list to a data table instance.
 
We can also gather some knowledge about Interop and how to access all the objects. interop and Reflection can help you, I think.
 
I am going to make this as a generic but you can use strongly typed as your need. (Also read all the comments in the code, I have tried to write what’s happening on each line).
  1. // T is a generic class  
  2. static DataTable ConvertToDataTable<T>(List<T> models)  
  3. {  
  4.     // creating a data table instance and typed it as our incoming model   
  5.     // as I make it generic, if you want, you can make it the model typed you want.  
  6.     DataTable dataTable = new DataTable(typeof(T).Name);  
  7.   
  8.     //Get all the properties of that model  
  9.     PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  10.   
  11.     // Loop through all the properties              
  12.     // Adding Column name to our datatable  
  13.     foreach (PropertyInfo prop in Props)  
  14.     {  
  15.         //Setting column names as Property names    
  16.         dataTable.Columns.Add(prop.Name);  
  17.     }  
  18.     // Adding Row and its value to our dataTable  
  19.     foreach (T item in models)  
  20.     {  
  21.         var values = new object[Props.Length];  
  22.         for (int i = 0; i < Props.Length; i++)  
  23.         {  
  24.             //inserting property values to datatable rows    
  25.             values[i] = Props[i].GetValue(item, null);  
  26.         }  
  27.         // Finally add value to datatable    
  28.         dataTable.Rows.Add(values);  
  29.     }  
  30.     return dataTable;  
  31. }  
So as of now our function looks like this,
 
 
Now the fun part begins. To export these datatables into an Excel object we have to add office interop reference to our project.
 
Microsoft.Office.Interop.Excel is part of Dotnet assemblies so you just need to attach to your project.
 
Reference > Assemblies > Extentions > Search Excel > Add the latest version..
 
 
Now turn over to ExcelExport.cs file and write a static method. I have named it as Generate Excel. Take two parameters. The first one is the data table instance that we have just created and a path that we are going to save our excel file (We are going to deal with it later) ..
  1. public static void GenerateExcel(DataTable dataTable, string path)  
  2. {  
  3. }  
We are going to use datasets and add our datatable instance to its Table property. If you want to know more about DataSet you can find it here.
  1. public static void GenerateExcel(DataTable dataTable, string path)  
  2. {  
  3.       
  4.     DataSet dataSet = new DataSet();  
  5.     dataSet.Tables.Add(dataTable);  
  6. }  
After this the process is quite simple. We have created an Excel app , Excel worksheet, workbook and added all of our rows and colums to it.
 
To keep it short we have to rename this as:
  1. public static void GenerateExcel(DataTable dataTable, string path)  
  2. {  
  3.       
  4.     DataSet dataSet = new DataSet();  
  5.     dataSet.Tables.Add(dataTable);  
  6.   
  7.     // create a excel app along side with workbook and worksheet and give a name to it  
  8.     Excel.Application excelApp = new Excel.Application();  
  9.     Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();  
  10.     Excel._Worksheet xlWorksheet = excelWorkBook.Sheets[1];  
  11.     Excel.Range xlRange = xlWorksheet.UsedRange;  
  12.     foreach (DataTable table in dataSet.Tables)  
  13.     {  
  14.         //Add a new worksheet to workbook with the Datatable name  
  15.         Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();  
  16.         excelWorkSheet.Name = table.TableName;  
  17.   
  18.         // add all the columns  
  19.         for (int i = 1; i < table.Columns.Count + 1; i++)  
  20.         {  
  21.             excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;  
  22.         }  
  23.   
  24.         // add all the rows  
  25.         for (int j = 0; j < table.Rows.Count; j++)  
  26.         {  
  27.             for (int k = 0; k < table.Columns.Count; k++)  
  28.             {  
  29.                 excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Now it's time for saving. So for this we can save it as its default Excel saved location that would be -> c:/users/{user-name}/documents/ but for this I have choose to save it my custom location. 
  1. // excelWorkBook.Save(); -> this is save to its default location  
  2. excelWorkBook.SaveAs(path); // -> this will do the custom  
  3. excelWorkBook.Close();  
  4. excelApp.Quit();  
So our Excel export class looks like this.
 
 
Now we have to call this method from our main method. To make this prettier I have included some operations in it.
  1. static void Main(string[] args)  
  2. {  
  3.     var userList = UserManager.SeedData();  
  4.     try  
  5.     {  
  6.         Console.WriteLine("Please select a operation to do ..");  
  7.         Console.WriteLine("1. Export Data as EXCEL");  
  8.         int command = Convert.ToInt32(Console.ReadLine());  
  9.         switch (command)  
  10.         {  
  11.             case 1:  
  12.                 string fileName = "UserManager.xlsx";  
  13.                 Console.WriteLine("Please give a location to save :");  
  14.                 string location = Console.ReadLine();  
  15.                 string customExcelSavingPath = location + "\\" + fileName;  
  16.                 ExcelExport.GenerateExcel(ConvertToDataTable(userList), customExcelSavingPath);  
  17.                 break;  
  18.             default:  
  19.                 break;  
  20.         }  
  21.     }  
  22.     catch (Exception ex)  
  23.     {  
  24.         throw ex;  
  25.     }  
  26. }  
And that's it!
 
So our main program.cs file should look like this.
 
 
I have uploaded all of this to this repository.
 
Happy Coding. 


Similar Articles