日期:2014-05-18  浏览次数:20578 次

如何将Excel数据导入数据库?急!!
由于采用的是nhibernate操作数据库,现在有一功能是要将Excel中的数据成批导入数据库,请各位高手指点方向!谢谢了!

------解决方案--------------------
用DTS
------解决方案--------------------
将Excel中的数据导入数据库的方法(Access),自己参考吧!

string excelConnectionString = "Provider = Microsoft.Jet.OleDb.4.0; Data Source = " + Server.MapPath( "abc.xls ") + " ; Extended Properties=Excel 8.0; ";
OleDbConnection excelConn = new OleDbConnection(excelConnectionString);
excelConn.Open();
OleDbCommand excelCmd = new OleDbCommand( "SELECT * FROM [Sheet1$] ", excelConn);

string accessConnectionString = "Provider = Microsoft.Jet.OleDb.4.0; Data Source = " + Server.MapPath( "data.mdb ");
OleDbConnection accessConn = new OleDbConnection(accessConnectionString);
accessConn.Open();
OleDbTransaction trans = accessConn.BeginTransaction();


string sql = "INSERT INTO [temp] (ABC) VALUES ( '{0} ') ";

try
{
using (OleDbDataReader excelDr = excelCmd.ExecuteReader())
{
while (excelDr.Read())
{
OleDbCommand accessCmd = new OleDbCommand(string.Format(sql, System.Convert.ToString(excelDr[0])), accessConn);
accessCmd.Transaction = trans;
accessCmd.ExecuteNonQuery();

}
}
trans.Commit();
Response.Write( "OK ");
}
catch (Exception ex)
{
trans.Rollback();
Response.Write( "NO " + ex.Message);
}
finally
{
excelConn.Close();
accessConn.Close();
}