1. 程式人生 > >C#用Odbc、Oledb查詢Excel和CSV

C#用Odbc、Oledb查詢Excel和CSV

        /// <summary>
        /// Oledb查詢Excel
        /// </summary>
        public static void QueryExcelToOledb()
        {
            //檔案路徑
            string tableName = "file.xls";
            string filePath = AppDomain.CurrentDomain.BaseDirectory + tableName;

            OleDbConnection oledbConn = new OleDbConnection();
            OleDbCommand oledbCmd = new OleDbCommand();
            OleDbDataReader dataReader;
            try
            {
                //一下兩種方式皆可
                //string strConnOledb = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=";
                //strConnOledb += filePath;
                //strConnOledb += ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";

                string strConnOledb = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
                strConnOledb += filePath;
                strConnOledb += ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";

                oledbConn.ConnectionString = strConnOledb;
                oledbConn.Open();
                StringBuilder commandText = new StringBuilder("SELECT ");
                commandText.AppendFormat("* From {0}", "[Sheet1$]");
                oledbCmd.Connection = oledbConn;
                oledbCmd.CommandText = commandText.ToString();
                dataReader = oledbCmd.ExecuteReader();
                while (dataReader.Read())
                {
                    string pContent = Convert.ToString(dataReader["content"]);
                }
                dataReader.Close();
            }
            catch (System.Exception ex)
            {
                oledbConn.Close();
            }
            finally
            {
                oledbConn.Close();
            }
        }