0

I extract data from all sheets in a workbook using the following code :

foreach (var sheetName in GetExcelSheetNames(connectionString))
            {
                if (sheetName.Contains("_"))
                {
                }
                else
                {
                    using (OleDbConnection con = new OleDbConnection(connectionString))
                    {

                        var dataTable = new DataTable();
                        string query = string.Format("SELECT  * ,{0} as sheetName FROM [{0}]", sheetName);
                        con.Open();
                        OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
                        try
                        {
                            adapter.Fill(dataTable);
                            ds.Tables.Add(dataTable);
                        }
                        catch { }
                    }
                }

I can't just figure how data are stocked in DataTable : sheetname is added as column ? how can I extract it ?

  foreach (DataTable dt in ds.Tables)
                    {
                            using (SqlConnection con = new SqlConnection(consString))
                            {
                                con.Open();
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {

                                    for (int j = 0; j < dt.Columns.Count; j ++)
                                    {
//what should I write here ?
                                    }
                                 }
                              }
  • did you debug and see what your dt(datatable) has? It clearly shows number columns and rows – prasy Jul 14 '15 at 13:36

2 Answers2

0

assuming dt is your datatable variable,

do dt.Rows[row index][column index]

like

dt[2][4] -> will reference the 2nd row, 4th cell

I am not sure, but perhaps the sheetname might be stored at dt.TableName

Veverke
  • 9,208
  • 4
  • 51
  • 95
0

In order to get the sheet name, using oledb, you will need to use code that looks something like this (thanks to this SO post and answer):

DataTable dtSheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
     List<string> sheets= new List<string>();
     foreach (DataRow dr in dtSheets.Rows)
     {
        if (dr["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
        {
             sheets.Add(dr["TABLE_NAME"].ToString());
        } 
     }

Below is how you access the values from a datatable:

var someValue = dt.Rows[i][j]

You need to get the item at the column index (j) of the row, at the row index (i), of the current datatable (dt).

Conversely, you can use the name of the column as well.

var someValue = dt.Rows[i]["columnName"]
Community
  • 1
  • 1
JasonWilczak
  • 2,303
  • 2
  • 21
  • 37