How to work with Excel (.xls) files in C#.NET?

H

1. Add reference to COM object Microsoft.Office.Excel 12.0 or any other available library.

2. Code:

using Microsoft.Office.Interop.Excel;

private void anyfunction()
{
   Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();

   Microsoft.Office.Interop.Excel.Workbook xlWkb = null;

   Microsoft.Office.Interop.Excel.Worksheet xlWks = null;

   xlWkb = xlapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @”Report.xls”, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
   xlWks = (Microsoft.Office.Interop.Excel.Worksheet)xlWkb.Worksheets[1];

   //Sample Statement to work on sheets
   xlWks.get_Range(“A2”, “H65000”).ClearContents();

   xlWkb.Close(true, Missing.Value, Missing.Value);
}

About the author

Nishant Bamb
By Nishant Bamb

Category