Andy 胡

导航

C#操作Excel

using System;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication2 {
    class Program {
        static void Main(string[] args) {

            const string C_XLS_PROVIDER = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
            const string C_XLSX_PROVIDER = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=";

            const string C_XLS_PROP = ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;\"";
            const string C_XLSX_PROP = ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1;\"";

            const string strPath = @"..\MyTable.xlsx";
            string sExt = System.IO.Path.GetExtension(strPath);

            OleDbConnection _conn = null;
            DataTable _dtSchema = null;
            OleDbDataAdapter _adapter = null;
            DataSet _ds = null;
            DataTable _dtbl = null;
            switch (sExt)
            {
                case ".xls":
                    _conn = new OleDbConnection(C_XLS_PROVIDER + strPath + C_XLS_PROP);
                    break;
                case ".xlsx":
                    _conn = new OleDbConnection(C_XLSX_PROVIDER + strPath + C_XLSX_PROP);
                    break;
                default:
                    Console.WriteLine("没有这种Excel");
                    break;
            }
            if (_conn == null)
            {
                return;
            }
            try
            {
                _conn.Open();

                _dtSchema = _conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                // 0 : TABLE_CATALOG
                // 1 : TABLE_SCHEMA
                // 2 : TABLE_NAME
                // 3 : TABLE_TYPE
                string tableName = _dtSchema.Rows[0][2].ToString().Trim();
                string strSql = "select * from [" + tableName + "]";

                _adapter = new OleDbDataAdapter(strSql, _conn);
                _ds = new DataSet();
                _adapter.Fill(_ds, tableName);//填充数据

                _dtbl = _ds.Tables[tableName];
                foreach (DataRow r in _dtbl.Rows)
                {
                    string s1 = r[0].ToString().Trim();
                    string s2 = r[2].ToString().Trim();
                    Console.WriteLine(s1 + " " + s2);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (_conn != null)
                {
                    _conn.Close();
                    _conn = null;
                }
            }

            Console.ReadKey();
        }
    }
}

 

posted on 2017-03-26 02:21  talkwah  阅读(154)  评论(0编辑  收藏  举报