[转]动态获取Excel表名

时间:2021-10-11 09:24:48
    public string GetExcelFirstTableName(string excelFileName)
    {
        string tableName = null;
        if (File.Exists(excelFileName))
        {
            using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet." +
                        "OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + excelFileName))
            {
                conn.Open();
                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    tableName += dt.Rows[i][2].ToString().Trim();
                }
            }
        }
        return tableName;
    }