среда, 6 июля 2011 г.

Reading a Excel Sheet using OLEDB Connection Object


/// 
        /// This function is used to read Excel Sheet using OLEDB connection
        /// 
        /// file name of the excel file
        public void ReadExcel(string filename)
        {
            try
            {
                //Create a OLEDB connection for Excel file
                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                            "Data Source=" + filename + ";" +
                                            "Extended Properties=Excel 8.0;";
                OleDbConnection objConn = new OleDbConnection(connectionString);
                objConn.Open();
                // Creating a command object to read the values from Excel file
                OleDbCommand ObjCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
                // Creating a Read object
                OleDbDataReader objReader = ObjCommand.ExecuteReader();
                // Looping through the values and displaying
                while (objReader.Read())
                {
                    MessageBox.Show(objReader[0].ToString() + " " + objReader[1].ToString());
                }
                //Disposing the objects
                objReader.Dispose();
                ObjCommand.Dispose();
                objConn.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Комментариев нет: