5

How do I get sheet name from Excel and add them to my comboBox list? I can't seem to add it in my code as it is in public static

public static DataTable ExcelToDataTable (string fileName)
{
    using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
    {
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            var result = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                UseColumnDataType = true,
                ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true
                }
            });
            DataTableCollection table = result.Tables;
            DataTable resultTable = table["Sheet1"];                 
            return resultTable;
        }
    }
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
  • Check if this question helps -> https://stackoverflow.com/questions/32521987/excelreaderfactory-reading-first-sheet – Am_I_Helpful Jan 16 '18 at 17:07

2 Answers2

4

If I understand what you want! you can use this code:

var sheetNames = result.Tables
    .OfType<DataTable>()
    .Select(c => c.TableName)
    .ToArray();
shA.t
  • 16,580
  • 5
  • 54
  • 111
1

You should use the TableName property

result.Tables[0].TableName

Tables is a collection with all your sheets so you can do a loop and pick all sheets names by index

Milton Filho
  • 525
  • 3
  • 17