Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / C#
Article

How to connect Excel DB using C# .Net

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Dec 2007CPOL 40K   13   2
Connect the Excel Tables using C# .net
Screenshot - XLSDB

Introduction

Get data from MS-Excel Using C# .Net

Using the code

Using this code you can get the data from MS-Excel. Its just a OLEDB connection as Follows
string Con_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_Path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";

in this DB_Path is the location of the .XLS file.

"HDR=Yes;" indicates that the first row contains columnnames, not data.

"HDR=No;" indicates the opposite.

"IMEX=1;" tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Anadocs IT Solutions Pvt Ltd
India India
M.Senthil Rajan,
Software Engineer,
Anadocs IT Solutions,
Chennai.

Comments and Discussions

 
Answerimport Excel files into DataGridView to Sql server Pin
Dinesh Ginagar5-Jun-15 0:17
Dinesh Ginagar5-Jun-15 0:17 
C#
//Step 1: Browse the Excel file 
//The Button(Browse) to "open the FileDialog Box" the path stored in your "Textbox1.text" my textbox name is "txtsearch.text" you can assign any name as your wish..
// 'DataTable' is the class stores the rows and columns of data.data comes any where from method,database,memory..
//getDataFromXLS(filepath)//reading data from excel Filepath(txtsearch.txt)

 private void button1_Click(object sender, EventArgs e)  
        {            
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                txtsearch.Text = ofd.FileName;
                DataTable test = getDataFromXLS(txtsearch.Text);  
                if (test != null)                                
                    dataGridView1.DataSource = test;             
            }     
        }
//Step 2: once the file path is assigned
//step 3: Toolbox->datagridview and resize as your wish
//step 3: Xl into Gridview
 private 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);    //set the new oledb connection as like sql           
                cnCSV.Open();                
                OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Sheet1$]", cnCSV);//here the oledbconnection where the sheet name is available or not.. if your sheet name is "test" change the setting as [test$] like..      
                OleDbDataAdapter daCSV = new OleDbDataAdapter();//oledbadapter it communicate between dataset and data sources with help of oledbconnection.
//oledbconnection object has no information data it retrives.same dataset has no knowledge datasource where the data commming from.
//oledbdataadapter manage the communicate the 2 obj..          
                daCSV.SelectCommand = cmdSelect;                    
                DataTable dtCSV = new DataTable();
                daCSV.Fill(dtCSV);               
                cnCSV.Close();
                daCSV = null;
                MessageBox.Show("Copied");                    
                return dtCSV;
             }
             catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return null;                   
                }               
           }
//Step 5: Grid view into DB

private void button1_Click_1(object sender, EventArgs e)
                {                    
       for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)//to read the date atlast row in gridview
                        {
   
  string Query = "Insert into EFCD_3013(Dok_Nr,Bl)Values('" + dataGridView1.Rows[i].Cells["Dok_Nr"].Value + "','" + dataGridView1.Rows[i].Cells["Bl"].Value + "')";// add the column as your wish. note : make your xl column name and sql column name are same.                          
                            try
                            {
                                string Connection = null;
                                Connection = "/*Your connection string*/";
                                SqlConnection Con = new SqlConnection(Connection);
                                Con.Open();
                                SqlCommand Cmd = new SqlCommand(Query, Con);                              
                                Cmd.ExecuteNonQuery();
                                Con.Close();
                                  
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }  }                                                                                              
                    }

GeneralBetter way Pin
FilipKrnjic9-Jul-09 5:44
FilipKrnjic9-Jul-09 5:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.