讀寫excel, EXCEL的資料轉存到ACCESS[代碼]

來源:互聯網
上載者:User

       
        //@@@@@@@@@@@@@@@@@@@@@@@@@@第一個範例@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
       
        //以下的代碼是從一個EXCEL中讀取資料,寫到ACCESS中。
        //引入EXCEL,在D盤建立一個EXCEL來源資料檔案,以及ACCESS的目標資料檔案

        public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties=Excel 5.0;";
            string strExcel = string.Format("select * from [{0}$]", strSheetName);
            DataSet ds = new DataSet();

            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                conn.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                adapter.Fill(ds, strSheetName);
                conn.Close();
            }

            return ds.Tables[strSheetName];
        }

        public static void InsertDataToAccess(OleDbConnection oleDbConn, string v0, string v1, string v2, string v3, string v4, string v5)
        {
            string strInsertString = "INSERT INTO t1 (id,[order],name,age,sex,demo) VALUES (@id,@order,@name,@age,@sex,@demo)";

            OleDbCommand oComm = new OleDbCommand(strInsertString, oleDbConn);

            oComm.Parameters.Add("@id", OleDbType.Char, 50);
            oComm.Parameters["@id"].Value = v0;

            oComm.Parameters.Add("@order", OleDbType.Char, 50);
            oComm.Parameters["@order"].Value = v1;

            oComm.Parameters.Add("@name", OleDbType.Char, 50);
            oComm.Parameters["@name"].Value = v2;

            oComm.Parameters.Add("@age", OleDbType.Char, 50);
            oComm.Parameters["@age"].Value = v3;

            oComm.Parameters.Add("@sex", OleDbType.Char, 50);
            oComm.Parameters["@sex"].Value = v4;

            oComm.Parameters.Add("@demo", OleDbType.Char, 50);
            oComm.Parameters["@demo"].Value = v5;
           
            oComm.ExecuteNonQuery();
           
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dtExcel = ExcelToDataTable("D://b.xls", "Sheet1");

            OleDbConnection oleDbConn = new OleDbConnection();
            oleDbConn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/A.mdb;User Id=admin;Password=;";
            oleDbConn.Open();

            for (int i = 0; i < dtExcel.Rows.Count-1; i++)
            {
                string nowTime = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
               
                InsertDataToAccess(oleDbConn,
                    dtExcel.Rows[i][0].ToString(),
                    dtExcel.Rows[i][1].ToString(),
                    dtExcel.Rows[i][2].ToString(),
                    dtExcel.Rows[i][3].ToString(),
                    dtExcel.Rows[i][4].ToString(),
                    nowTime
                    );
            }
            oleDbConn.Close();

            //@@@@@@@@@@@@@@@@@@@@@@@@@@第二個範例@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            //以下的代碼是對一個EXCEL檔案的讀寫操作
            //代碼使用基本條件
            //*using System.Reflection; // 引用這個才能使用Missing欄位
            //*需要使用EXCEL外部參考
            //MISSING的作用是,通過反射產生一個函數的預設參數
            //在寫外來對象組件操作過程中,有時對調用的方法中不用的參數調用Null錯誤,填充此參數即可。
           
           
            //功能開始
           
            Excel.Application xApp = new Excel.ApplicationClass();
            xApp.Visible = true;
           
           
            //得到WorkBook對象, 可以用兩種方式之一: 下面的是開啟已有的檔案

            Excel.Workbook xBook = xApp.Workbooks._Open(@"D:/B.xls",
            Missing.Value, Missing.Value, Missing.Value, Missing.Value
            , Missing.Value, Missing.Value, Missing.Value, Missing.Value
            , Missing.Value, Missing.Value, Missing.Value, Missing.Value);
           
            //第二種方式  建立一個XLS檔案
            //Excel.Workbook xBook = xApp.Workbooks.Add(Missing.Value);

            //取得當前xls檔案的SHEET,第一句是取第一個,第二句是取活動的。
            Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1];
            //Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet;

            //讀取資料,通過Range對象

            Excel.Range rng1 = xSheet.get_Range("A1",Type.Missing);
           
            //讀取,通過Range對象,但使用不同的介面得到Range
            Excel.Range rng2 = (Excel.Range)xSheet.Cells[3, 1];
            Console.WriteLine(rng2.Value2);

            //寫入資料
            //無論是Range屬性,Cells,Rows,Columns這些屬性,其類型都是Excel.Range,都有Value2這個屬性
            //Value得到它的值.   Value2則是針對數位.

            Excel.Range rng3 = xSheet.get_Range("C6", Missing.Value);
            rng3.Value2 = 4;
            rng3.Interior.ColorIndex = 4; //設定Range的背景色(綠色)

            ////儲存方式一:儲存WorkBook
            //xBook.SaveAs(@"D:/CData.xls",
            //Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            // Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
            // Missing.Value, Missing.Value);

            ////儲存方式二:儲存WorkSheet
            //xSheet.SaveAs(@"D:/CData2.xls",
            //Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            // Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            //儲存方式三
            xBook.Save();

            xSheet = null;
            xBook = null;
            xApp.Quit(); //這一句是非常重要的,否則Excel對象不能從記憶體中退出
            xApp = null;

            //@@@@@@@@@@@@@@@@@@@@@@@@@@第三個範例@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
            /**
             * 這是一個基於C#的對ACCESS資料庫進行增刪改查的程式,運行可以通過。
             *
             * 但我覺得程式結構上還不太最佳化,比如:
             *
             * 1、OleDbCommand odCommand = odcConnection.CreateCommand()和odCommand.CommandText = strSql;能不能單獨提出來?
             *
             * 2、做一個功能比較全面的方法,只需要兩個參數(conn,sql)能執行所有的SQL文。遇到更新、插入、刪除還能把件數報出來。
             *
             * 3、INSERT 和 UPDATE 語句如果欄位特別特別多,拼SQL文時,能不能做簡化處理,比如用?來代替,象JAVA那樣。怎麼實現啊。
             *
             * 4、怎麼做能讓DB串連這部分功能,獨立出來(做成基底,包括ACCESS、SQL、ORACLE)以後再用的時候,只要添上參數,就能跑SQL.
             *
             **/

            //建立一個接續,初期化
            OleDbConnection conn = initConn();

            //做查詢
            string strSql = "select * from t1";
            SelectSta(conn, strSql);

            //做更新
            string strupdate = "update t1 set age = 12";
            UpdateStatus(conn, strupdate);

            //做插入
            string strrecorder = "4,3,'tom',43,1,'ddd'";
            string strinsert = "insert into t1 values(" + strrecorder + ")";//能不能改改,這樣太彆扭了。
            InsertStatus(conn, strinsert);

            //做刪除
            string strDel = "delete from t1 where age <> '12'";
            DeleteStatus(conn, strDel);
            conn.Close();
        }

        //查詢處理
        private void SelectSta(OleDbConnection odcConnection, string strSql)
        {
            OleDbCommand odCommand = odcConnection.CreateCommand();
            odCommand.CommandText = strSql;
            OleDbDataReader odrReader = odCommand.ExecuteReader();
            ArrayList Arr = new ArrayList();
            while (odrReader.Read())
            {
                Arr.Add(odrReader["NAME"].ToString());
                listBox1.Items.Add(odrReader["NAME"].ToString());
            }
        }

        //更新處理
        private void UpdateStatus(OleDbConnection conn, string strupdate)
        {
            OleDbCommand odCommand = conn.CreateCommand();
            odCommand.CommandText = strupdate;
            int intCnt = odCommand.ExecuteNonQuery();
            MessageBox.Show("一共有【"+intCnt+"】條資料被更新!");
        }

        //刪除處理
        private void DeleteStatus(OleDbConnection conn, string strDel)
        {
            OleDbCommand odCommand = conn.CreateCommand();
            odCommand.CommandText = strDel;
            int intCnt = odCommand.ExecuteNonQuery();
            MessageBox.Show("一共有【" + intCnt + "】條資料被刪除!");
        }

        //插入處理
        private void InsertStatus(OleDbConnection conn, string strinsert)
        {
            OleDbCommand odCommand = conn.CreateCommand();
            odCommand.CommandText = strinsert;
            int intCnt = odCommand.ExecuteNonQuery();
            MessageBox.Show("一共有【" + intCnt + "】條資料被插入!");
        }

        //初始串連
        private OleDbConnection initConn()
        {
            string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/A.mdb";
            OleDbConnection odcConnection = new OleDbConnection(strConn);
            odcConnection.Open();
            return odcConnection;
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.