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.
- class Program
- {
- static void Main(string[] args)
- {
- Application xlApp = new Application();
-
- if (xlApp == null)
- {
-
- return;
- }
-
-
- Workbook xlWorkBook;
- Worksheet xlWorkSheet;
- object misValue = System.Reflection.Missing.Value;
-
- xlWorkBook = xlApp.Workbooks.Add(misValue);
- xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);
- xlWorkSheet.Cells[1, 1] = "Sheet 1 content";
-
-
- xlWorkBook.SaveAs("f:\\csharp-Excel.xls", XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
- xlWorkBook.Close(true, misValue, misValue);
- xlApp.Quit();
-
- releaseObject(xlWorkSheet);
- releaseObject(xlWorkBook);
- releaseObject(xlApp);
-
-
- }
-
-
- private static void releaseObject(object obj)
- {
- try
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
- obj = null;
- }
- catch (Exception ex)
- {
- obj = null;
- }
- finally
- {
- GC.Collect();
- }
- }
- }
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.