Import Data from Excel to DataGridView in C#

First need to add the reference “Microsoft.Office.Interop.Excel”. You can add it from .Net components.
Add an open Dialog box control, Datagridview1, Textbox control and two Command buttons on form
using Excel = Microsoft.Office.Interop.Excel;
                                                                       
private voidbutton1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog()==DialogResult.OK)
                textBox1.Text=openFileDialog1.FileName;
        }
private voidbutton2_Click(object sender, EventArgs e)
{
     try
            {
                System.Data.OleDb.OleDbConnectionMyCnn ;
                System.Data.DataSet DSet ;
                System.Data.OleDb.OleDbDataAdapterMyCmd ;
MyCnn = new System.Data.OleDb.OleDbConnection(“provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + textBox1.Text + ” ;Extended Properties=Excel 8.0;”);
                MyCmd = new System.Data.OleDb.OleDbDataAdapter 
                (“select * from [Sheet1$]”, MyCnn);
                MyCmd.TableMappings.Add(“Table”, “TestTable”);
                DSet = new System.Data.DataSet();
                MyCmd.Fill(DSet);
                dataGridView1.DataSource = DSet.Tables[0];
                MyCnn.Close();
            }
            catch (Exceptionex)
            {
                MessageBox.Show (ex.ToString());
            }
 }

Output :

2 Comments on “Import Data from Excel to DataGridView in C#”

  1. Hi ! I tried to use this code but i´m getting an error "System.Data.OleDb.OleDbExcepion(0x80004005)……."
    I´m using office 2010 and win8 64bits.
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *