How to read excel file in C#

By FoxLearn 7/16/2024 8:55:14 AM   10.05K
To read Excel files (.xls or .xlsx) using the ExcelDataReader library in a C# application, follow these steps.

Open your Visual Studio, then click 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

How to read excel file in C#

To read an Excel file with the .xls extension using ExcelDataReader in a C# Windows Forms application, you first need to install the ExcelDataReader package via NuGet Package Manager by right-clicking on your project select Manage NuGet Packages -> Search ExcelDataReader -> Install

c# exceldatareader

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

Design your form as below

c# read excel file

Add code to handle your form as below

DataSet result;

// c# read excel file
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];
}

In this example, when the user clicks the Open button (btnOpen_Click event), an OpenFileDialog is shown to select an Excel file, then use ExcelDataReader to read an excel file in c#.

VIDEO TUTORIAL

Related