Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi Friends,

I am doing one task reading data from excel and need to find columns header and respective Data type for contain data based on max value of the columns .

C#
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", s);
                   string flag = "";
                   using (OleDbConnection con = new OleDbConnection(connString))
                   {
                       using (OleDbCommand cmd = new OleDbCommand())
                       {
                           //Read the First Sheet
                           cmd.Connection = con;
                           con.Open();
                           DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                           con.Close();
                           string firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

                           //Read the Header Row
                           cmd.CommandText = "SELECT   * From [" + firstSheet + "]";

                           using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                           {
                               DataTable HeaderColumns = new DataTable();
                               da.SelectCommand = cmd;
                               da.Fill(HeaderColumns);
                               //DataSet ds = new DataSet();
                               //da.Fill(ds);
                               //ds.WriteXml(@"D:\test1.xml");

                               foreach (DataColumn column in HeaderColumns.Columns)
                               {

            string columnName = HeaderColumns.Rows[0][column.ColumnName].ToString();

            string coltyp = HeaderColumns.Rows.ToString();

                               }

Can you please any one help to achieve this.

regards
Arul.R
Posted
Updated 15-Feb-15 17:39pm
v2

1 solution

Instead of defining HDR=No why not let the driver to get the column names (Hdr=YEs). Using this the column names in your datatable should correspond the ones in Excel.

What comes to the maximum values, after filling the datatable, selct the max using a dataview [^]. Something like
C#
...
   DataTable AllData = new DataTable();
   da.SelectCommand = cmd;
   da.Fill(AllData);
   AllData.DefaultView.Sort = "ColumnName DESC"
...

For more info, see DataView.Sort[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900