Getting the first sheet from an Excel document regardless of sheet name with OleDb

前端 未结 9 623
青春惊慌失措
青春惊慌失措 2020-12-29 02:23

I have users that name their sheets all sorts of crazy things, but I want to be able to get the first sheet of the Excel document regardless of what it is named.

I

相关标签:
9条回答
  • 2020-12-29 02:45

    It`s my solution ▼ (Easy, Fast, Executable, Understandable)

    internal static DataTable GetExcelSheet(string excelFile,string sheetName = "")
    {
        string fullPathToExcel = Path.GetFullPath(excelFile);
        string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel " + (excelFile.ToLower().EndsWith("x") ? "12.0" : "8.0") + ";HDR=yes'", fullPathToExcel);
        return GetDataTable(connString, "SELECT * FROM [" + (string.IsNullOrEmpty(sheetName) ? GetTableName(connString, 0) : sheetName + "$") + "]");
    }
    
    private static DataTable GetDataTable(string connectionString, string sql)
    {
        DataTable dt = new DataTable();
    
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            conn.Open();
            using (OleDbCommand cmd = new OleDbCommand(sql, conn))
            {
                using (OleDbDataReader rdr = cmd.ExecuteReader())
                {
                    dt.Load(rdr);
                    return dt;
                }
            }
        }
    }
    private static string GetTableName(string connectionString, int row = 0)
    {
        OleDbConnection conn = new OleDbConnection(connectionString);
        try
        {
            conn.Open();
            return conn.GetSchema("Tables").Rows[row]["TABLE_NAME"] + "";
        }
        catch { }
        finally { conn.Close();}
        return "sheet1";
    }
    
    0 讨论(0)
  • 2020-12-29 02:50

    You can use the GetOleDbSchemaTable (VB) or GetOleDbSchemaTable (C#).

    Using the Tables Enum it will return a list of all the worksheet names, which you can then use to dynamically build the required SQL.

    You can use:

    MySchemaTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

    All the Worksheets names will be returned as part of a DataTable you can them itterate through.

    Using the OleDbSchemaGuid information can be retrieved on

    • Columns
    • Foreign keys
    • Indexes
    • Primary keys
    • Tables
    • Views

    Full MSDN documentation available here

    0 讨论(0)
  • 2020-12-29 02:53

    ended up using this:

    using (OleDbConnection conn = new OleDbConnection(connString))
    {
        conn.Open();
        dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
        Sheet1= dtSchema.Rows[0].Field<string>("TABLE_NAME");
    }
    
    0 讨论(0)
提交回复
热议问题