Solved

Assigning headers to a datatable

Posted on 2009-05-12
3
266 Views
Last Modified: 2012-05-06
I am reading a table of data into excel using ado.net.  Unfortunately my data and the headers for that data are separated on the excel sheet(the headers are actually several hundred rows below the start of the data)  I use the below code to import the table into a datatable and it works wonderfully.  How would I get the header data from the "header" table to become the header for the "data" table?
myDataSet = new DataSet();

            filename = "";
 

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.FileName = ""; // Default file name

            dlg.DefaultExt = ".xls"; // Default file extension

            dlg.Filter = "Excel documents (.xls)|*.xls"; // Filter files by extension
 

            // Show save file dialog box

            Nullable<bool> result = dlg.ShowDialog();
 

            string file;

            if (result == true)

            {

                // Open document

                file = dlg.FileName;

                int filedel = file.LastIndexOf("\\");

                filename = file.Remove(0, filedel+1);

            }

            //else end function

            else

            {

                return;

            }
 
 

            string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties= ";

        connectString = connectString+ @"""Excel 8.0;HDR=YES;""";
 
 
 

            OleDbConnection connection =

                    new OleDbConnection(connectString);
 

            string query = "SELECT * FROM [Lap Sim$B24:FG724] "; //where (NOT ([Bank] IS NULL))

            string queryheader = "SELECT * FROM [Lap Sim$B751:FG751] "; //where (NOT ([Bank] IS NULL))

            

            

            OleDbConnection myAccessConn = null;

            try

            {

                myAccessConn = new OleDbConnection(connectString);

            }

            catch(Exception ex)

            {

                  Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);

                  return;

            }

 

            try

            {
 

                OleDbCommand myAccessCommand = new OleDbCommand(query, myAccessConn);

                  OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

 

                  myAccessConn.Open();

                  myDataAdapter.Fill(myDataSet,"data");
 
 
 

                  myAccessCommand = new OleDbCommand(queryheader, myAccessConn);

                  myDataAdapter = new OleDbDataAdapter(myAccessCommand);
 

                  //myAccessConn.Open();

                  myDataAdapter.Fill(myDataSet, "header");

 

            }

            catch (Exception ex)

            {

                  Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);

                  return;

            }

            finally

            {

                myAccessConn.Close();

                connection.Close();

            }
 

  

            cmbXAxis.Items.Clear();

            cmbYAxis.Items.Clear();

            foreach (DataColumn column in myDataSet.Tables["data"].Columns)

            {

                string colname = column.ColumnName.ToString();

                cmbXAxis.Items.Add(colname);

                cmbYAxis.Items.Add(colname);

            }

            
 

        }

Open in new window

0
Comment
Question by:perrytaylor
  • 2
3 Comments
 
LVL 19

Accepted Solution

by:
Rimvis earned 500 total points
ID: 24371843
Like this?
...
            finally
            {
                myAccessConn.Close();
                connection.Close();
            }
            
            //Rename columns
            for (int i = 0; i < myDataSet.Tables["header"].Columns.Count; i++)
            {
                DataColumn dc = myDataSet.Tables["data"].Columns[i]; 
                dc.Caption = dc.ColumnName = myDataSet.Tables["header"].Columns[i].ColumnName;
            }
...

Open in new window

0
 

Author Closing Comment

by:perrytaylor
ID: 31580631
This is actually what I came up with that seems to work,  what is the dc.caption all about?
thanks

string name;
            for(int b = 0; b
0
 
LVL 19

Expert Comment

by:Rimvis
ID: 24373694
"dc.Caption = dc.ColumnName =" sets same value for both Caption and ColumnName properties. I was not sure which property you are referring as "header "
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
coded character set iptc field within a jpeg 1 67
Excel file not created as expected 7 46
Filename to be appended with DateTimeof Download 3 40
Error on link 14 36
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

947 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now