C# - 使用 OLEDB读取 excel(不用Excel对象).

参考: How to read from an Excel file using OLEDB

为了使用方便,我做成了工具类(OledbCommon.cs),好以后使用.

注:连接字符串中,Provider=xx是从这个连接模仿,主要是考虑是否把第1行当成表头: http://www.connectionstrings.com/excel/

OledbCommon.cs类的代码:

using System;

using System.Collections.Generic;

using System.Data.OleDb;

using System.Data;



namespace Oledb

{

    /// <summary>

    /// 连接 excel(支持.xlsx).

    /// </summary>

    class OledbCommon

    {

        public enum Version { XLS, XLSX }    //保留:不同版本差异.



        public string FileName { get; private set; }



        //连接字符串.

        private string connectString = null;

        public string ConnectString { get { return connectString; } }



        /// <summary>

        /// if contains header.

        /// </summary>

        readonly bool hasHeader = false;

        public bool HasHeader { get { return hasHeader; } }



        /// <summary>

        /// Initialize connection string.

        /// </summary>

        /// <param name="fileName">full file name.</param>

        /// <param name="hasHeader">ture if the .xls file contains header;otherwise false.</param>

        public OledbCommon(string fileName, bool hasHeader)

        {

            if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");

            FileName = fileName;

            this.hasHeader = hasHeader;

            connectString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';", FileName);



            //specify it contains header.

            if (HasHeader)

                connectString += "Extended Properties='Excel 12.0 Xml;HDR=YES'";

            else

                connectString += "Extended Properties='Excel 12.0 Xml;'";

        }



        /// <summary>

        /// 获得"连接对象'.

        /// </summary>

        /// <returns></returns>

        public OleDbConnection GetConnection()

        {

            return new System.Data.OleDb.OleDbConnection(connectString);

        }



        /// <summary>

        /// 获得数据集-根据'sql'语句和连接对象..

        /// </summary>

        /// <param name="sql">值得注意的是,表名后面要有'$'符号.如,select * from [t$]</param>

        /// <param name="connection"></param>

        /// <returns></returns>

        public DataSet GetDataSet(string sql, OleDbConnection connection)

        {



            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);

            DataSet set = new DataSet();

            adapter.Fill(set);

            return set;

        }



        public DataTable GetDataTable(string sql, OleDbConnection connection) {

            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);

            DataTable t = new DataTable();

            adapter.Fill(t);

            return t;

        }



        /// <summary>

        /// Get DataRows by specified column-name.

        /// </summary>

        /// <param name="set">The input set.</param>

        /// <param name="columnName">The specified column-name</param>

        /// <returns></returns>

        public List<DataRow> GetDataRow(DataSet set, string columnName)

        {

            DataTable t = set.Tables[0];    //get the first table as default.

            List<DataRow> rows = new List<DataRow>();

            foreach (DataRow r in t.Rows)

            {

                rows.Add((DataRow)r[columnName]);

            };

            return rows;

        }



        /// <summary>

        /// 执行Reader方法:注意,执行这个方法需要重写本类的'ExecuteWithinReader'方法,该方法默认为空实现.

        /// </summary>

        /// <param name="sql"></param>

        public void ExecuteReader(string sql)

        {

            using (OleDbConnection conn = GetConnection())

            {

                conn.Open();

                using (OleDbCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = sql;

                    using (OleDbDataReader r = cmd.ExecuteReader())

                    {

                        while (r.Read())

                        {

                            ExecuteWithinReader();  //需要在子类中重写这个方法.

                        }   //while.

                    }   //cmd.

                }

            }   //connection.

        }



        /// <summary>

        /// 在Reader中待实现的代码.例如,计数器的增加,或取得某字段的值等.

        /// </summary>

        protected virtual void ExecuteWithinReader()

        {

            //todo:例如,计数器的增加,或取得某字段的值.

        }



        /// <summary>

        /// 获取全部Sheet名.

        /// </summary>

        /// <returns></returns>

        public List<string> GetSheetNames()

        {

            List<string> namesResult = new List<string>();  //存储结果.

            using (OleDbConnection conn = GetConnection())

            {

                conn.Open();

                DataTable sheetNames = conn.GetOleDbSchemaTable

           (System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                foreach (DataRow dr in sheetNames.Rows)

                {

                    namesResult.Add(dr[2].ToString());

                }

            }



            return namesResult;

        }

    }

}

 

 

 

主调用代码:

1 string fileName = @"D:\cs\office\excel\excel_data\tmp.xls";

2             string sql = "select [姓名] from [msg$]"; //(***要注意后面要有'$'符号,且最后有[]包围,防止关键字冲突) 可以在sql 语句指定列字段.

3             OledbCommon ole = new OledbCommon(fileName, true);

4             using (OleDbConnection conn = ole.GetConnection()) {

5                 DataSet set = ole.GetDataSet(sql, conn);

6                 dgv.DataSource = set.Tables[0];

7             }

运行的效果:C# - 使用 OLEDB读取 excel(不用Excel对象).

你可能感兴趣的:(Excel)