今天,有个项目需要核对一些数据,核对Excel文件中的某一列数据是否存在于数据库中的某个表,这查询起来实在太烦,虽然只有千把条记录,逐个到数据库里查,也要花个大半天时间。于是写了个小工具,将Excel文件中需要的列读出来,写入到数据库中,项目中用的是IBM DB2,这个可以根据需要进行修改,然后再进行表联合查询,就省事多了。
我访问Excel文件使用的方式是OleDB方式,没有用Office组件。
首先加入namespace:

usingSystem.Data.OleDb;
定义连接字符串:

stringfilePath=@"c:\employee.xls";
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+filePath+";ExtendedProperties='Excel8.0;HDR=Yes;IMEX=1;'";
选择Excel文件中的一个sheet,比如叫“EmployeeInfo”:

stringstrSheetName="EmployeeInfo";
stringstrExcel="select*from["+strSheetName+"$]";
打开连接,读取Excel文件中数据到Dataset中,然后关闭连接:

OleDbConnectionconn=newOleDbConnection(strConn);
conn.Open();
OleDbDataAdapteradapter=newOleDbDataAdapter(strExcel,conn);
DataSetds=newDataSet();
adapter.Fill(ds,"data");
conn.Close();
写到DB2数据库中,假定数据库已经建好,并且表TEST也已经建好:

stringconnString="Provider=IBMDADB2;Database=TOOLSDB"+
";HOSTNAME=localhost;PROTOCOL=TCPIP;PORT=50000;uid=db2admin;pwd=123456;";
OleDbConnectiondb2Conn=newOleDbConnection(connString);
OleDbCommanddb2Comm=newOleDbCommand();
db2Conn.Open();
db2Comm.Connection=db2Conn;
db2Comm.CommandTimeout=600;
for(inti=0;i<ds.Tables[0].Rows.Count;i++)
{
stringeID=ds.Tables[0].Rows[i]["员工号"].ToString();
stringeName=ds.Tables[0].Rows[i]["员工姓名"].ToString();
stringeDate=ds.Tables[0].Rows[i]["入职日期"].ToString();
stringePosition=ds.Tables[0].Rows[i]["职位"].ToString();
db2Comm.CommandText="INSERTINTOTEST(ID,Name,Date,Position)VALUES('"+
eID.ToString()+"','"+eName.ToString()+"','"+eDate.ToString()+"','"+
ePosition.ToString()+"');";
db2Comm.ExecuteNonQuery();
}
db2Conn.Close();
这样就把Excel表中的数据插入到数据库中了。