Create Excel File Using C#

Here I will explain how you can use C# code to write things to Excel. Certainly, there are several good pre-made plugins available which directly write your output to an Excel file. This is more like learning the old school way of how it was done.
 
Create a simple Console Application to interop excel dll.

 
 
Now, you can paste this code in your class.
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.              Application xlApp = new Application();  
  6.   
  7.             if (xlApp == null)  
  8.             {  
  9.                 //just to check if we get hold of the excel aplication  
  10.                 return;  
  11.             }  
  12.   
  13.   
  14.             Workbook xlWorkBook;  
  15.             Worksheet xlWorkSheet;  
  16.             object misValue = System.Reflection.Missing.Value;  
  17.   
  18.             xlWorkBook = xlApp.Workbooks.Add(misValue);  
  19.             xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);  
  20.             xlWorkSheet.Cells[1, 1] = "Sheet 1 content";  
  21.             //you can basically do what every you want  
  22.   
  23.             xlWorkBook.SaveAs("f:\\csharp-Excel.xls", XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  
  24.             xlWorkBook.Close(true, misValue, misValue);  
  25.             xlApp.Quit();  
  26.   
  27.             releaseObject(xlWorkSheet);  
  28.             releaseObject(xlWorkBook);  
  29.             releaseObject(xlApp);  
  30.               
  31.   
  32.         }  
  33.   
  34.         //so that we dont leave any memory leaks  
  35.         private static void releaseObject(object obj)  
  36.         {  
  37.             try  
  38.             {  
  39.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);  
  40.                 obj = null;  
  41.             }  
  42.             catch (Exception ex)  
  43.             {  
  44.                 obj = null;  
  45.             }  
  46.             finally  
  47.             {  
  48.                 GC.Collect();  
  49.             }  
  50.         }  
  51.     }  
This will create a file and write the sample text in it. The file won't even be visible. So, everything is done in the background.
Ebook Download
View all
FileInfo in C#
Read by 9.7k people
Download Now!
Learn
View all