C# 获得Excel工作簿Sheet页面(工作表)集合的名称

         #region 获取Excel工作薄中Sheet页(工作表)名集合
        /// <summary> 
        /// 获取Excel工作薄中Sheet页(工作表)名集合
        /// </summary> 
        /// <param name="excelFile">Excel文件名称及路径,EG:C:UsersJKDesktop导入測试.xls</param> 
        /// <returns>Sheet页名称集合</returns> 
        private String[] GetExcelSheetNames(string fileName)
        {
            OleDbConnection objConn = null;
            System.Data.DataTable dt = null;
            try
            {
                string connString=string.Empty;
                string FileType =fileName.Substring(fileName.LastIndexOf("."));
                if (FileType == ".xls")  
                 connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
                else//.xlsx
                    connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";  
                // 创建连接对象 
                objConn = new OleDbConnection(connString);
                // 打开数据库连接 
                objConn.Open();
                // 得到包括数据架构的数据表 
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;
                // 加入工作表名称到字符串数组 
                foreach (DataRow row in dt.Rows)
                {
                    string strSheetTableName = row["TABLE_NAME"].ToString();
                    //过滤无效SheetName
                    if (strSheetTableName.Contains("$")&&strSheetTableName.Replace("'", "").EndsWith("$"))
                    {
                        excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length - 1);
                    }                   
                    i++;
                }
                return excelSheets;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return null;
            }
            finally
            {
                // 清理 
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }
        #endregion

版权声明:笔者:jiankunking 资源:http://blog.csdn.net/jiankunking 本文版权归作者和CSDN合伙人,欢迎转载。但是,如果没有从本节宣布提交权限必须保留,并连接到原来的文章页给出视在位置。

原文地址:https://www.cnblogs.com/bhlsheji/p/4708266.html