简体   繁体   中英

How to get sheet name from Excel

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;
        }
    }
}

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

var sheetNames = result.Tables
    .OfType<DataTable>()
    .Select(c => c.TableName)
    .ToArray();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM