Click here to Skip to main content
15,885,537 members
Articles / Desktop Programming / Windows Forms

How to Read Microsoft Excel 2007 Using a Connection String in C#

Rate me:
Please Sign up or sign in to vote.
4.52/5 (17 votes)
28 Nov 2007CPOL1 min read 277.9K   11.1K   94  
This article explains how to connect to Microsoft Excel 2007 using a connection string and populate DataGridView
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


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

        private void btnPopulate_Click(object sender, EventArgs e)
        {
            // You can change C:\Members.xlsx to any path where 
            // the file is located.
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
               Data Source=C:\Members.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";

            // if you don't want to show the header row (first row)
            // use 'HDR=NO' in the string

            string strSQL = "SELECT * FROM [Sheet1$]";

            OleDbConnection excelConnection = new OleDbConnection(connectionString);
            excelConnection.Open(); // This code will open excel file.

            OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);

            // create data table
            DataTable dTable = new DataTable();
            dataAdapter.Fill(dTable);

            // bind the datasource
            dataBingingSrc.DataSource = dTable;

            // assign the dataBindingSrc to the DataGridView
            dgvExcelList.DataSource = dataBingingSrc;

            // dispose used objects
            dTable.Dispose();
            dataAdapter.Dispose();
            dbCommand.Dispose();

            excelConnection.Close();
            excelConnection.Dispose();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Dhivehisoft
Maldives Maldives
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions