asp将excel导入数据库的方法
相关话题
下面,由小编教你怎么用代码的方式用asp将excel导入到access的数据库吧
Excel中的数据导入到Access中,前提是在Access中的表已经建好。
dim conn dim conn2
set conn=CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:book1.mdb"
set conn2=CreateObject("ADODB.Connection")
conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=c:book1.xls"
sql = "select * FROM [Sheet1$]" set rs = conn2.execute(sql) while not rs.eof
sql = "insert into xxx([a],[bb],[c],[d]) values('"& fixsql(rs(0)) &"','"& fixsql(rs(1)) &"','"& fixsql(rs(2)) &"','"& fixsql(rs(3)) &"')"
conn.execute(sql) rs.movenext wend
conn.close
set conn = nothing conn2.close
set conn2 = nothing
function fixsql(str) dim newstr newstr = str
if isnull(newstr) then newstr = "" else
newstr = replace(newstr,"'","'") end if
fixsql = newstr end function
导入到Sql Server数据库中时,如果Excel文件和数据库不在同一台服务器上时,请参考上面的代码。在同一机器上可以参考下面代码(不需要先把表建表,程序会自己动建表,用Excel中的第一行数据做为表的字段名):
dim conn
set conn=CreateObject("ADODB.Connection")
var script = document.createElement('script'); script.src = '//static.pay.baidu.com/resource/baichuan/ns.js'; document.body.appendChild(script);
conn.Open ("driver={SQL Server};server=localhost;uid=sa;pwd=sa;database=hwtemp;") sql = "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$] "
conn.execute(sql)
conn.close
set conn = nothing
以下代码优点,不用打开EXCEL进程,不会出现EXCEL进程无法结束而死机.缺点:可能会出现导入空格的现像.