如何将excel里的数据导入SQL
如T 需代码
------解决方案--------------------代码在里面
http://support.microsoft.com/kb/321686/zh-cn
------解决方案--------------------将Excel的数据导入SQL server :
-- ======================================================
SELECT * into newtable
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0 ',
'Data Source= "c:\book1.xls ";User ID=Admin;Password=;Extended properties=Excel 5.0 ')...[Sheet1$]
实例:
SELECT * into newtable
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0 ',
'Data Source= "c:\Finance\account.xls ";User ID=Admin;Password=;Extended properties=Excel 5.0 ')...xactions
------解决方案----------------------如果接受数据导入的表已经存在
insert into 表 select * from
OPENROWSET( 'MICROSOFT.JET.OLEDB.4.0 '
, 'Excel 5.0;HDR=YES;DATABASE=c:\test.xls ',sheet1$)
--如果导入数据并生成表
select * into 表 from
OPENROWSET( 'MICROSOFT.JET.OLEDB.4.0 '
, 'Excel 5.0;HDR=YES;DATABASE=c:\test.xls ',sheet1$)
------解决方案--------------------程序导入还是要做工具导入?
------解决方案--------------------//Excel文件的连接
string excelConnectionString = "Provider = Microsoft.Jet.OleDb.4.0; Data Source = " + Excel文件路径 + " ; 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 = " + 数据库路径;
OleDbConnection accessConn = new OleDbConnection(accessConnectionString);
accessConn.Open();
OleDbTransaction trans = accessConn.BeginTransaction();
string sql = "INSERT INTO [表] (字段) 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();
}
catch (Exception ex)
{
//添加失败,回滚事务
trans.Rollback();
}
finally
{
//关闭数据库连接
excelConn.Close();
accessConn.Close();
}
------解决方案--------------------public string sConnectionString
{
get
{ //先将EXCEL导入到数据库,一:先把EXCEL导入dateView,二:然后将dateView里的数据导入到数据库里面
//string xlsPath = Server.MapPath( "~/app_data/book1.xls ");
//EXCEL 的连接串
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source= " + File1.PostedFile.FileName.ToString() + &qu