获取Excel中的第一个工作表名称

有时候需要批量将Excel中的数据导入到数据库中,这时就需要获取Excel文件中的工作表名称,由于很多文件都只有第一个工作表有数据,而第一个工作表的命名方式也不一样,比如有的是英文命名,有的是中文命名,有的网友提供了下面的方法来获取所有工作表的名称

 /// <summary>
        /// 读取Excel中表的名称
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        public String[] GetExcelSheetNames(string excelFile)
        {

            OleDbConnection objConn = null;
            System.Data.DataTable dt = null;
            try
            {
                //此连接可以操作.xls与.xlsx文件  
                string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFile + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
                objConn = new OleDbConnection(strConn);
                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)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    i++;
                }
                return excelSheets;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }

这种方法可以获取Excel中所有工作表的名称,但是得到的结果是经过排序的,不是按照Excel中的工作表顺序返回的,因此无法得到第一个工作表的名称。下面这种方法经过测试,可以获取第一个工作表名称:

Microsoft.Office.Interop.Excel.Application obj = default(Microsoft.Office.Interop.Excel.Application);
Microsoft.Office.Interop.Excel.Workbook objWB = default(Microsoft.Office.Interop.Excel.Workbook);
string FirstSheetName = null;
obj = (Microsoft.Office.Interop.Excel.Application)Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", string.Empty);
objWB = obj.Workbooks.Open(filepath, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
Type.Missing,Type.Missing, Type.Missing, Type.Missing,  
Type.Missing, Type.Missing,Type.Missing, Type.Missing);
FirstSheetName = ((Microsoft.Office.Interop.Excel.Worksheet)objWB.Worksheets[1]).Name;
objWB.Close(Type.Missing, Type.Missing, Type.Missing);
objWB = null;
obj.Quit();
obj = null;
原文地址:https://www.cnblogs.com/neverstop/p/2762493.html