Import Excel to Datagridview using C#

In this tutorial, I will show you how to import an excel file to a DataGridview using C#. We are going to be using Microsoft.Office.interop.Excel namespace in this project. There are many ways to read an excel file in C#, but this is the easy way I found for beginners like me. Just follow the steps below.

Before we start, make sure that you have Visual Studio installed on your machine. If not, you can visit this download link. You can download the community version for free.

Let’s Start:

  1. First, Create a new Windows forma project. Navigate to File. Choose New option. Select Project.
Import Excel to Datagridview using C#
New project

2. From the New Project window. Name your project in any way you want. In my case, I name my project Upload_Data_From_Excel. Proceed on clicking the “Ok” button. See the image below.

Import Excel to Datagridview using C#
Name Project (Upload_Data_From_Excel)

3. Add controls from the toolbox. What we need is a Form, buttons, and OpenFileDialog.

  • Form
  • Button -> for the upload click event.
  • OpenFileDialog -> for browsing files.
  • DataGridview ->for viewing of data

Below image is the UI I created. This will help you visualize and understand the next step.

Import Excel to Datagridview using C#
Create design
  1. For clarity and easy navigating, we will rename our button. Click the button you added to your form and go to its property from the solution explorer and change the value. In my case, I name it as btn_Upload.
Import Excel
Change button name

5. Now navigate to your solution explorer and right-click on Reference, choose Add Reference, and then add Microsoft.Office.Interop.Excel.

Import Excel
Add Reference

6. From the reference manager window, expand Assemblies, and click Extensions from the left pane and search for Microsoft.Office.Interop.Excel from the middle pane.

Import Excel
Add Microsoft Office Interop

7. Verify if the reference is added. Go to your project solution explorer. Expand Reference, then look for Microsoft.Office.Interop.Excel.

Import Excel
Check Reference if Added

8. After we verify and successfully added Microsoft.Office.Interop.Excel. Open your form design and double click on the btn_Upload button to add button click event.

Import Excel
Double Click on button upload

9. Copy and paste the code below to your btn_Upload Click Event.

string file = ""; //variable for the Excel File Location
DataTable dt = new DataTable(); //container for our excel data
DataRow row;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Check if Result == "OK".
{
  file = openFileDialog1.FileName; //get the filename with the location of the file
  try {
    //Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file

    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

    Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);

    Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];

    Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;

    int rowCount = excelRange.Rows.Count; //get row count of excel data

    int colCount = excelRange.Columns.Count; // get column count of excel data

    //Get the first Column of excel file which is the Column Name

    for (int i = 1; i <= rowCount; i++) {
      for (int j = 1; j <= colCount; j++) {
        dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
      }
      break;
    }

    //Get Row Data of Excel

    int rowCounter; //This variable is used for row index number
    for (int i = 2; i <= rowCount; i++) //Loop for available row of excel data
    {
      row = dt.NewRow(); //assign new row to DataTable
      rowCounter = 0;
      for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
      {
        //check if cell is empty
        if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null) {
          row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
        }
        else {
          row[i] = "";
        }
        rowCounter++;
      }
      dt.Rows.Add(row); //add row to DataTable
    }

    dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview

    //close and clean excel process
    GC.Collect();
    GC.WaitForPendingFinalizers();
    Marshal.ReleaseComObject(excelRange);
    Marshal.ReleaseComObject(excelWorksheet);
    //quit apps
    excelWorkbook.Close();
    Marshal.ReleaseComObject(excelWorkbook);
    excelApp.Quit();
    Marshal.ReleaseComObject(excelApp);
  }
  catch(Exception ex) {
    MessageBox.Show(ex.Message);
  }
  1. Now you are ready to run your project and test if no error occurs. Run your application by pressing ctrl + f5 without debugging or f5 for debugging mode.
  • Click Upload button to upload.
Import Excel
Run Project
  • Then select your excel file. See the image below.
Import Excel
Open File

This is how to Import Excel to Datagridview using C# code. Hopes this helps.

Final output:

Excel File:

Import Excel
Excel File

Project Output:

Import Excel
Final Output

Full Code:

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

namespace Upload_Data_From_Excel
{
    public partial class Upload_Data_Frm_EXCEL : Form
    {
        public Upload_Data_Frm_EXCEL()
        {
            InitializeComponent();
        }

        private void btn_upload_Click(object sender, EventArgs e)
        {
         string file = "";   //variable for the Excel File Location
            DataTable dt = new DataTable();   //container for our excel data
            DataRow row;
            DialogResult result = openFileDialog1.ShowDialog();  // Show the dialog.
            if (result == DialogResult.OK)   // Check if Result == "OK".
            {
                file = openFileDialog1.FileName; //get the filename with the location of the file
                try

                {
                 //Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file

                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                    Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);

                    Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];

                    Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;


                    int rowCount = excelRange.Rows.Count;  //get row count of excel data

                    int colCount = excelRange.Columns.Count; // get column count of excel data

                        //Get the first Column of excel file which is the Column Name                  

                    for (int i = 1; i <= rowCount; i++)
                    {
                        for (int j = 1; j <= colCount; j++)
                        {
                            dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
                        }
                            break;
                    }                       
                        //Get Row Data of Excel              
                    int rowCounter;  //This variable is used for row index number
                    for (int i = 2; i <= rowCount; i++) //Loop for available row of excel data
                    {
                        row = dt.NewRow();  //assign new row to DataTable
                        rowCounter = 0;
                        for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
                        {
                             //check if cell is empty
                            if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)
                            {
                                row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
                            }
                            else
                            {
                                row[i] = "";
                            }
                           
                            rowCounter++;
                        }
                        dt.Rows.Add(row); //add row to DataTable
                    }

            dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview

                   //Close and Clean excel process
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    Marshal.ReleaseComObject(excelRange);
                    Marshal.ReleaseComObject(excelWorksheet);
                    excelWorkbook.Close();
                    Marshal.ReleaseComObject(excelWorkbook);

                    //quit 
                    excelApp.Quit();
                    Marshal.ReleaseComObject(excelApp);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

        }

    }

}

Thank you for reading! Happy Coding!!

If you are interested in ASP.NET Core you may visit my Blog page for my latest post.

Also Read: Ethernut telecommunications