Tuesday, October 4, 2011

How to import data from excel to datatable in c#

protected void button1_Click(object sender, EventArgs e)
{
DataTable test = getDataFromXLS("c:\\xl2xml.xls");
if (test != null)
grid.DataSource = test;
grid.DataBind();
}


protected DataTable getDataFromXLS(string strFilePath)
{
try
{
string strConnectionString = "";
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strFilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
cnCSV.Open();
OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Insurance_Aging$]", cnCSV);
OleDbDataAdapter daCSV = new OleDbDataAdapter(); daCSV.SelectCommand = cmdSelect;
DataTable dtCSV = new DataTable();
daCSV.Fill(dtCSV);
cnCSV.Close();
daCSV = null;
return dtCSV;
}
catch (Exception ex)
{
return null;
}
finally { }
}



Import Excel to DataTable
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=911149&SiteID=1
http://support.microsoft.com/kb/815142/en-us
http://msdn2.microsoft.com/en-us/library/ms178685.aspx
http://support.microsoft.com/kb/306572/
http://samples.gotdotnet.com/quickstart/aspplus/doc/configformat.aspx
http://support.microsoft.com/kb/316675/en-us http://msdn.microsoft.com/library/default.asp?url=/library/en-

No comments:

Post a Comment