0

I'm using SQL to query Excel File as HERE, and I know I can get the content of worksheet by something like:

var ds = new DataSet();
var conn = new OleDbConnection();
conn.Open();
var cmd = new OleDbDataAdapter("Select * FROM [Sheet1$]", conn);
cmd.Fill(ds, "ds1");

and I want to ask is there way to get all table names?

I've tried this answer but not working.

yu yang Jian
  • 6,680
  • 7
  • 55
  • 80

3 Answers3

1

Are you asking about getting data from all sheets? If yes, then please see below post:

How to import all the Excel sheets to DataSet in C#

Dhiren
  • 153
  • 1
  • 13
1

I tried the code from the example link and it works for me:

            var result = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                UseColumnDataType = true,
                ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });

            DataTableCollection tables = result.Tables;

            for (int i = 0; i < tables.Count; i++)
            {
                Console.WriteLine(tables[i].TableName);
                //here I can work with current table
                for (int j = 0; j < tables[i].Columns.Count; j++)
                {
                    Console.WriteLine(tables[i].Columns[j].ColumnName);
                }
            }
Alexey
  • 21
  • 5
0

I just find a way to get all worksheets name by:

var ds = new DataSet();
var conn = _connNoHeader = new OleDbConnection(string.Format("Provider={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=No;\";Data Source={1}", provider, filePath));           
conn.Open();

DataTable tables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, 
                                             new object[] { null, null, null, "TABLE" });

Console.WriteLine("The tables are:");
foreach (DataRow row in tables.Rows)
    Console.Write("  {0}", row[2]);

// here are all worksheet name
var allWorksheetNames = tables.Rows.OfType<DataRow>().Select(row => row[2].ToString().TrimEnd('$')).ToList();

This solution comes from HERE.

Other answers are also helpful!

yu yang Jian
  • 6,680
  • 7
  • 55
  • 80