C# 读取EXCEL数据

  
   /// <summary>
        /// 读取EXCEL数据
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static System.Data.DataSet ExcelToDS(string Path)
        {
            string strConn = string.Empty;
            string version = Path.Substring(Path.Length - 1);
            if (version.Equals("s"))
            {
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            }
            else
            {
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
            }
            OleDbConnection conn = new OleDbConnection(strConn);
            System.Data.DataSet ds = null;
            try
            {
                conn.Open();
                //System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new Object[] { null, null, null, "TABLE" });
 
                string tableName = schemaTable.Rows[0][2].ToString().Trim();
                string strExcel = "";
                OleDbDataAdapter myCommand = null;
                strExcel = "select * from [" + tableName + "]";
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                ds = new System.Data.DataSet();
                myCommand.Fill(ds, tableName);
                return ds;
            }
            catch (Exception e) { conn.Close(); }
            finally { conn.Close(); }
            return ds;
 
        }
原文地址:https://www.cnblogs.com/su-king/p/5122041.html