简体   繁体   English

如何从Excel获取工作表名称

[英]How to get sheet name from Excel

How do I get sheet name from Excel and add them to my comboBox list? 如何从Excel获取工作表名称并将其添加到我的组合框列表中? I can't seem to add it in my code as it is in public static 我似乎无法在我的代码中添加它,因为它在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 您应该使用TableName属性

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 表是包含所有工作表的集合,因此您可以循环并按索引选择所有工作表名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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