Import DataTable To Excel C#
Import DataTable To Excel C#
control in c#.
– Start a new project in your visual studio in C#.
– Add reference of Microsoft ADO Ext. 2.8 from .net COM component. We will use this library
to extract all Excel Sheet from Excel file.
– Add a windows form in your project, add a Datagridview control and use the following code
snippets.
– Use Open Dialog box control So that we can browse and excel file. Set Open Dialog control
Filter = “Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*”, so that it will filter browse only Excel files.
This Excel file can contain more than one Sheet. You need to add another form to show all excel
sheets name so that user can select any one excel sheet which he want to import.
Write the following code on Page Load event of that from on which you want to show all excel
sheet list
By the following function we can find the total sheets in Excel file.
public static string[] GetTableExcel(string strFileName)
{
string[] strTables = new string[100];
Catalog oCatlog = new Catalog();
ADOX.Table oTable = new ADOX.Table();
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
strFileName + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=1\";", "", "", 0);
oCatlog.ActiveConnection = oConn;
if (oCatlog.Tables.Count>0)
{
int item = 0;
foreach (ADOX.Table tab in oCatlog.Tables)
{
if (tab.Type == "TABLE")
{
strTables[item] = tab.Name;
item++;
}
}
}
return strTables;
}
Select any sheet from above list and click on Import button.
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = "
+ strFileName + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=1\";");
conn.Open();
string strQuery = "SELECT * FROM [" + Table + "]";
System.Data.OleDb.OleDbDataAdapter adapter = new
System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataSet ds = new System.Data.DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
Author: Ankur
Have worked primarily in the domain of Calling, CRM and direct advertisers services. My
technological forte is Microsoft Technologies especially Dot Net (Visual Studio 2003, 2005,
2008, 2010 and 2012) and Microsoft SQL Server 2000,2005 and 2008 R2. My Area of Expertise
is in C#. Net, VB.Net, MS-SQL Server, ASP. Net, Silverlight, HTML, XML, Crystal Report, Active
Reports, Infragistics, Component Art, ComponeOne, Lead Tools etc.View all posts by Ankur
Sumber : http://www.authorcode.com/import-data-from-excel-to-datagridview-in-c/