Subscribe to Recent Solutions        RSS Feed
-----

Load Excel File to Data Table using C Sharp.Net

Icon Leave Comment
I saw in forums everyone is asking how to load data from excel file to database.

I made a simple function to load excel data into DataTable, once you loaded data to DataTable you can move it to any database you want.

this function required excel file path to load data and you can modify excel sheet name if it is not matching with the code.

public DataTable Excel(string filePath)
{
try
{
OleDbConnection excelConnection = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + filePath + ";" +
"Extended Properties=Excel 8.0");

excelConnection.Open();

OleDbCommand excelSelectCommand = new OleDbCommand("SELECT * FROM [Sheet1$]");
excelSelectCommand.Connection = excelConnection;

OleDbDataAdapter adapter = new OleDbDataAdapter(excelSelectCommand);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
catch (Exception ex)
{
return null;
}
}


Example:

string filePath = Application.startupPath + @"\Book.xls";
dgShow.dataSource = Excel(filePath);

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)