Read Excel File in C#

In this article we will learn how to read an excel sheet from C#. We will use a basic excel file. Read the contents and display them to the console. The sample example uses Office 365 Excel COM Interop objects.

In order to use Excel objects in a .NET program you have to first add Excel Interop assembly as a reference to the project. Right click on the references node in the project solution explorer and click Add Reference. Select Microsoft.Office.Interop.Excel assembly as shown below in the Reference Manager and click OK.

Adding Microsoft.Office.Interop.Excel as Reference.

Once Excel Interop assembly is added as a reference to the project, open the code file (in our example case: Program.cs file) in which you want to use excel objects and add the below using statement.

    using Excel = Microsoft.Office.Interop.Excel;

In our example we will use the following Excel file.

Sample.xlsx contents

Complete Example Code

The following example code opens the excel file in the Bin/Debug directory of the application and its contents are displayed in the console. Excel sheet contents are shown in the below screen.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelInterop
    public class Program
        static void Main(string[] args)
            // Reference to Excel Application.
            Excel.Application xlApp = new Excel.Application();

            // Open the Excel file.
            // You have pass the full path of the file.
            // In this case file is stored in the Bin/Debug application directory.
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("Sample.xlsx"));

            // Get the first worksheet.
            Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);

            // Get the range of cells which has data.
            Excel.Range xlRange = xlWorksheet.UsedRange;

            // Get an object array of all of the cells in the worksheet with their values.
            object[,] valueArray = (object[,])xlRange.get_Value(

            // iterate through each cell and display the contents.
            for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
                for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col)
                    // Print value of the cell to Console.
                   Console.WriteLine(valueArray[row, col].ToString());

            // Close the Workbook.

            // Relase COM Object by decrementing the reference count.

            // Close Excel application.

            // Release COM object.



Example Output