Excel File Handling

We can handle Excel files using our C# Code. Excel files are different from other files because it is having multi dimensional contents(Rows and Columns). Before entering code part we need to follow some preliminary steps to handle excel files where adding the Excel file reference(Same like adding DLL file) is the first step.

Excel Handling Reference Manager

CODE

EG 1 . Reading, Writing values in Excel file using C# Code.

//We can give name to our Namespaces(Below we named as Excel). We referred Excel namespaces below so that no need to call it each time.
using Excel = Microsoft.Office.Interop.Excel;

namespace projectName{
    class Program {
        static void Main() {
            //------ 1. Writing Content in Excel sheet ------
            Excel.Application xlapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
            Excel.Workbook wb = xlapp.ActiveWorkbook;
            Excel.Worksheet ws = wb.ActiveSheet;
            ws.Cells[100, 1] = "CodersCapsule";

            //------ 2. Reading Excel sheet ------
            Excel.Application xlapp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Excel.Application;
            Excel.Workbook wb = xlapp.ActiveWorkbook;
            Excel.Worksheet ws = wb.Sheets[3];
            string valueInCell = ws.Cells[1, 1].value;
            Console.WriteLine(valueInCell);
        }
    }
}

(Click Here, For more exercises)