.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> File Operation >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Function to import excel data

Posted By:Rajshree       Posted Date: October 25, 2010    Points: 15    Category: File Operation    URL: http://www.dotnetspark.com  

here is a simple function used to export excel data Function takes 2 argument path of excel file and the name of sheet whose data you want to imp-ort
 

 protected DataTable ImportExcelData(string excelFilePath_, string sheetName_)
        {
            //specify the sheet name you want to read
            string strSheetName = sheetName_;

            System.Data.OleDb.OleDbConnection MyConnection = null;
            System.Data.OleDb.OleDbDataAdapter MyCommand = null;
            DataSet excelData = null;
            try
            {
                MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source='" + excelFilePath_ + "'; Extended Properties=Excel 8.0;");
                //Select the data from Sheet1 of the workbook.
                MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + strSheetName + "$]", MyConnection);

                excelData = new DataSet();
                MyCommand.Fill(excelData);

                return excelData.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (MyConnection != null && MyConnection.State == ConnectionState.Open)
                {
                    MyConnection.Close();
                    MyConnection.Dispose();
                }
                if (excelData != null)
                { 
                    excelData.Dispose();
                }
            }
        }


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend