Windows Forms: How to read excel file in C#

How to read excel (*.xls) file using ExcelDataReader in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadExcelFile" and then click OK

read excel file in c#Step 2: Right click on your project select Manage NuGet Packages -> Search ExcelDataReader -> Install

ExcelDataReader

Lightweight and fast library written in C# for reading Microsoft Excel files (2.0-2007).

Step 3: Design your form as below

c# read excel file

Step 4: Add code to handle your form as below

using Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReadExcelFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DataSet result;

        private void btnOpen_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog ofd = new OpenFileDialog() { Filter="Excel Workbook|*.xls", ValidateNames = true })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    //Read excel file
                    FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
                    IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
                    reader.IsFirstRowAsColumnNames = true;
                    result = reader.AsDataSet();
                    cboSheet.Items.Clear();
                    //Add sheet to combobox
                    foreach (DataTable dt in result.Tables)
                        cboSheet.Items.Add(dt.TableName);
                    reader.Close();
                }
            }
        }

        private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Select sheet
            dataGridView.DataSource = result.Tables[cboSheet.SelectedIndex];
        }
    }
}

VIDEO TUTORIALS