Tuesday, August 11, 2009

Load Data from Excel File to DataGridView



To read data from excel file and load that data into DataGridView, this function will take file name as parameter and reads that excel file

Controls Required: DataGridView


using System.Data.OleDb;
using System.IO;

public void setExcelFileAsDataSourceToDataGridView(string FileName)
{
OleDbConnection ocon;
OleDbDataAdapter oda;
DataSet ds;

//Check Whether file is xls file or not
if (Path.GetExtension(FileName) == ".xls")
{
try
{
//Create a OLEDB connection for Excel file
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;"+"Data Source=" + FileName + ";" + "Extended Properties=Excel 8.0;";
oCon = new OleDbConnection(conStr);
oda = new OleDbDataAdapter("select * from [Sheet1$]",oCon);
ds = new DataSet();

//Fill the Data Set
oda.Fill(ds);
//Set DataSource of DataGridView
dataGridView1.DataSource = ds.Tables[0];
ds.Dispose();
oda.Dispose();
oCon.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please select Excel File");
}
}

...

No comments:

Post a Comment

Followers