How to get list of ONLY excel worksheet names in Excel using OLEDB; filter out non-worksheets that show up in metadata

前端 未结 4 2196
眼角桃花
眼角桃花 2020-12-28 22:05

I have an issue getting worksheet names from an Excel spreadsheet using OLEDB. The problem is that when I use GetOleDbSchemaTable, the resulting DataTable has more than jus

相关标签:
4条回答
  • 2020-12-28 22:14

    The first way that comes to my mind is the same way akash88 listed in your link to Using Excel OleDb to get sheet names IN SHEET ORDER link.

    You can take akash88's approach and clean it up a little so the code is nicer to read.

            var wsList = from s in schemaTable
                         where s.Field<string>("TABLE_NAME").Contains("$")
                         select s.Field<string>("TABLE_NAME");
    
    0 讨论(0)
  • 2020-12-28 22:19

    From experience, it seems to be all those whose name ends in a dollar sign. I've come across scenarios from clients where extra worksheets seemed to be appearing which weren't present in the data - these later turned out to be hidden worksheets in Excel!

    0 讨论(0)
  • 2020-12-28 22:27

    The question is old, but for those who found it now, the skipping can be done as Jim found...

    // skip those that do not end correctly
    foreach (DataRow row in schemTable.Rows)
    {
        string sheetName = row["TABLE_NAME"].ToString();
        if (!sheetName.EndsWith("$") && !sheetName.EndsWith("$'"))
            continue;
        Console.WriteLine(sheetName);
    }
    

    That is the wanted are or those that end with $ or those that end with $'.

    0 讨论(0)
  • 2020-12-28 22:29

    You can test EndsWith("$") instead of Contains("$") like below:

    List<String> lstsheetNames = new List<String>();
    String sheetName;
    foreach (DataRow row in schemaTable.Rows)
    {
        sheetName = row.Field<string>("TABLE_NAME");
        String strTemp = sheetName.Split(' ');
    
        if(strTemp.Length == 1 && sheetName.EndsWith("$"))
           lstsheetNames.Add(sheetName.Substring(0, sheetName.Length - 1));
    
        else if(strTemp.Length > 1 && strTemp.GetValue(strTemp.Length - 1).ToString().EndsWith("$'"))
           lstsheetNames.Add(sheetName.Substring(1, sheetName.Length - 3));
    }
    

    I have used this code in a same problem and it works fine.

    Edit : Sorry,I did not pay attention to this.I changed the code now.It might not the best or shortest way but it works.

    0 讨论(0)
提交回复
热议问题