Excel 작업 3

10519 단어 Excel
 OleDbConnection connection;

        // 
        public void OpenConnection(string xlsFils) {
            if (!File.Exists(xlsFils))
            {
                MessageBox.Show(" \"" + xlsFils + "\" ", " ");

                return;
            }
            string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + xlsFils + ";Extended Properties=Excel 8.0";
            connection = new OleDbConnection(conn);
            connection.Open();
        }

        // 
        public DataTable Select()
        {
            DataTable dt = new DataTable();
            string Sql = "select * from [Sheet1$]";
            OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, connection);
            mycommand.Fill(dt);
            return dt;
        }
         

        private void Form1_Load(object sender, EventArgs e)
        {
            string xlsFile = System.Windows.Forms.Application.StartupPath + "/" + "ExcelFiles/test.xls";
            OpenConnection(xlsFile);
        }

        // 
        public void Insert()
        {
            string sql = string.Format("insert into [Sheet1$] values('{0}','{1}','{2}')", " ", " ", "520");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            Insert();
        }

        //Excel SQl , 
        public void Delete()
        {
            string sql = string.Format("Update [Sheet1$] set col1=NULL,col2=NULL,col3=NULL where col1='{0}'", " ");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        // 
        private new void Update() {
            string sql = string.Format("update  [Sheet1$] set col1='{0}' where col1='{1}'", " "," ");
            OleDbCommand myCommand = new OleDbCommand(sql, connection);
            myCommand.ExecuteNonQuery();
            Select();
        }
        private void btUpdate_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            Select();
        }

좋은 웹페이지 즐겨찾기