C#中获取Excel文件的第一个表名

//    2.以数据库方式打开并输入数据
//      此方式将xls文件所在目录看作数据库,其中的xls文件看作数据库表,表名即文件名(不加扩展名)。
//      函数importExcelToDataSet(string FilePath,string sheet)功能:从xls中读出数据到DataSet中,并返回DataSet对象。

        private DataSet importExcelToDataSet(string FilePath/*即文件目录的路径*/, string sheet/*表名即文件名(不加扩展名)*/)
        {

            string strConn;

            string getsheet;

            getsheet = "SELECT * FROM [" + sheet + "]" ;

            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";Extended Properties=Excel 8.0;";

            OleDbConnection conn = new OleDbConnection(strConn);

            OleDbDataAdapter myCommand = new OleDbDataAdapter(getsheet, strConn);

            DataSet myDataSet = new DataSet();

            try
            {

                myCommand.Fill(myDataSet);

            }

            catch (Exception ex)
            {

                MessageBox.Show("该Excel文件的工作表的名字不正确," + ex.Message);

            }

            return myDataSet;

        }


        /// <summary>
        /// C#中获取Excel文件的第一个表名 
        /// Excel文件中第一个表名的缺省值是Sheet1$, 但有时也会被改变为其他名字. 如果需要在C#中使用OleDb读写Excel文件, 就需要知道这个名字是什么. 以下代码就是实现这个功能的:
        /// </summary>
        /// <param name="excelFileName"></param>
        /// <returns></returns>
        public static 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);
                    tableName = dt.Rows[0][2].ToString().Trim();
                }
            }
            return tableName;
        }

原文地址:https://www.cnblogs.com/skyay/p/5752846.html