转贴:
先讀取EXCEL中的數據
private void btnView_Click(object sender, System.EventArgs e)
{
dgExcelData.DataSource = null;
FileDialog dlgOpen = new OpenFileDialog();
dlgOpen.Filter="Excel Files (*.xls)|*.xls";
if(dlgOpen.ShowDialog() == DialogResult.OK)
{
txtPath.Text=dlgOpen.FileName;
string strCon = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+txtPath.Text.Trim()+";Extended Properties=Excel 8.0" ;
OleDbConnection myConn = new OleDbConnection();
try
{
this.Cursor = Cursors.WaitCursor;
//創建一個數據Excel連接******************************************************************
myConn = new OleDbConnection ( strCon ) ;
string strCom = " SELECT * FROM [Sheet1$]" ;
myConn.Open ();
//打開連接得到數據集合
oDS.Clear();
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ;
myCommand.Fill ( oDS , "[Sheet1$]" ) ;
//關閉連接
myConn.Close ( ) ;
if (!oDS.Tables[0].Columns.Contains("Insert Result"
)
oDS.Tables[0].Columns.Add("Insert Result"
;
dgExcelData.SetDataBinding(oDS,"[Sheet1$]"
;
btnOk.Enabled = true;
this.Cursor = Cursors.Arrow;
inifrom();
}
catch(Exception err1)
{
MessageBox.Show(err1.Message);
myConn.Close();
this.Cursor = Cursors.Arrow;
}
}//END
}
上传至数据库下面上传的是oracle的,你将连接字串改一下就可以了,还是里面的sql语句也要改哦!
private void btnOk_Click(object sender, System.EventArgs e)
{
int nRowCount = oDS.Tables[0].Rows.Count;
int nCountPass = 0;
int nCountFail = 0;
string sql = "";
string sCon = "Provider=MSDAORA;Data Source=kssfis;User Id=mes_ks1;Password=mes_ks1;";
OleDbConnection cn = new OleDbConnection(sCon);
cn.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbTransaction Tran = cn.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = Tran;
//Tran.Begin();
for(int i =0;i<nRowCount;i++)
{
try
{
sql = "insert into bwc.erp_temp( part_no, erp_qty)";
sql += " values('"+oDS.Tables[0].Rows
[0].ToString().Trim()+"',"+oDS.Tables[0].Rows[1].ToString().Trim()+"";
cmd.Connection = cn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
nCountPass++;
oDS.Tables[0].Rows.Delete();
this.Text="[ PASS:"+nCountPass+" ] [ FAIL:"+nCountFail+" ]";
}
catch(Exception ex)
{
oDS.Tables[0].Rows[4] = ex.Message;
nCountFail++;
this.Text="[ PASS:"+nCountPass+" ] [ FAIL:"+nCountFail+" ]";
}
prebar.Value = i;
}
cmd.Transaction.Commit();
企业管理器里直接导入Excel表格