C# Write Data To Excel File
This example shows how to write data to an excel file using C#. To achive this, firstly, we need to add a reference to the dynamic link library for Excel which is called Microsoft.Office.Interop.Excel.dll. Firstly, go to your solution explorer and click on add a reference. Then, add Microsoft.Office.Interop.Excel.dll.
Also you must add the using to the following code.
using Excel = Microsoft.Office.Interop.Excel;
Usage:
public void WriteSample() { Excel.Application excelApp = new Excel.Application(); if (excelApp != null) { Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(); Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets.Add(); excelWorksheet.Cells[1, 1] = "Value1"; excelWorksheet.Cells[2, 1] = "Value2"; excelWorksheet.Cells[3, 1] = "Value3"; excelWorksheet.Cells[4, 1] = "Value4"; excelApp.ActiveWorkbook.SaveAs(@"C:\abc.xls", Excel.XlFileFormat.xlWorkbookNormal); excelWorkbook.Close(); excelApp.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorksheet); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorkbook); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp); GC.Collect(); GC.WaitForPendingFinalizers(); } }