2、或者將上述的excel表格嵌入在winform程序窗口里實(shí)現(xiàn)在EXcel表格里輸入數(shù)據(jù)及新增按鈕和保存按鈕來保存的功能。
你干嘛不把excel編輯好了以后再導(dǎo)入數(shù)據(jù)庫呢?這方面比較容易實(shí)現(xiàn),要想在excel中編程和數(shù)據(jù)庫交互比較困難。
winform中可以使用datagrid控件實(shí)現(xiàn)excel的編輯功能,這個(gè)和數(shù)據(jù)庫交互很容易實(shí)現(xiàn)。
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.xls|";
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.ShowDialog();
this.textBox1.Text = ofd.FileName.ToString();
}
private void btnInsert_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; " + "Data Source =" + this.textBox1.Text + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string sql = "Select * FROM [Sheet1$]";
try
{
myConn.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(sql, myConn);
oda.Fill(ds, "[Sheet1$]");
myConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
string server = this.txtServer.Text.Trim();
string db = this.txtDB.Text.Trim();
string username = this.txtUserName.Text.Trim();
string userpwd = this.txtUserPwd.Text.Trim();
//這里的連接用來將數(shù)據(jù)寫入SQLDB
string connectionString = @"server="+server+"; database="+db+"; uid="+username+";pwd="+userpwd+"";
SqlConnection con = new SqlConnection(connectionString);
string sqlGetAllDB = "select * from tb_Lot";
SqlDataAdapter daAllDB = new SqlDataAdapter(sqlGetAllDB, con);
DataSet dsAllDB = new DataSet();
DataGrid mygrid = new DataGrid();
mygrid.BeginInit();
mygrid.Location = new System.Drawing.Point(10, 240);
mygrid.Width = 1020;
mygrid.Height = 300;
this.Controls.Add(mygrid);
mygrid.EndInit();
mygrid.SetDataBinding(ds, "[Sheet1$]");
try
{
int num = ds.Tables[0].Rows.Count;
for (int i = 0; i < num; i++)
{
string ch1 = mygrid[i, 0].ToString();
string ch2 = mygrid[i, 1].ToString();
string ch3 = mygrid[i, 2].ToString();
string strii = "select * into from" + ds.Tables[0].TableName;
string strsql = "insert into tb_Lot values('" + ch1 + "','" + ch2 + "','" + ch3 + "')";
con.Open();
System.Data.DataTable dt = new System.Data.DataTable("tb_Lot");
SqlDataAdapter da = new SqlDataAdapter(strsql, con);
da.Fill(dt);
this.lblmessage.Text = "數(shù)據(jù)導(dǎo)入成功!";
this.groupBox2.Visible = true;
daAllDB.Fill(dsAllDB, "tb_Lot");
this.dataGridView1.DataSource = dsAllDB.Tables[0];
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("數(shù)據(jù)庫連接失!");
}
}
還不如這樣直接將Excel的數(shù)據(jù)導(dǎo)入的數(shù)據(jù)庫表中,在Excel里面來操作的話難度比較高。這方法我自己用過,可以將Excel的數(shù)據(jù)逐條導(dǎo)入的表中,前提是Excel的列數(shù)和表中的字段必須對應(yīng)。樓主可以研究下EXCEL里的VBA,順便再看看VBA里的ADODB.