using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Data;

namespace CNAS_DBSync
{
    public static class MdbHelper
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger("MdbHelper");
        /// <summary>
        /// 读取Excel第一个工作表的内容
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static Dictionary<string, DataTable> ReadAccessTables(string strPath,string strUser,string strPwd)
        {
            Dictionary<string, DataTable> dictTables = new Dictionary<string, DataTable>();
            try
            {
                //连接字符串
                //string connstring = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';");
                //string connstring = string.Format("Provider = Microsoft.Jet.OLEDB.4.0; Data Source={0}; User id={1};Jet OLEDB:Database Password={2}", strPath,strUser,strPwd);
                string connstring = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=False;Jet OLEDB:Database Password={1}",strPath,strPwd);
                using (OleDbConnection conn = new OleDbConnection(connstring))
                {
                    conn.Open();
                    DataTable TablesName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字

                    string sql = "";
                    OleDbDataAdapter ada = null;
                    foreach (DataRow dr in TablesName.Rows)
                    {
                        string strTableName = dr[2].ToString();

                        sql = string.Format("SELECT * FROM [{0}]", strTableName); //查询字符串
                        ada = new OleDbDataAdapter(sql, connstring);
                        DataSet set = new DataSet();
                        ada.Fill(set);

                        dictTables.Add(strTableName, set.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                //发生异常，写入日志
                log.Error(ex.Message);
            }
            return dictTables;
        }

    }
}
