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],[b],[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")
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
<%
Option Explicit
Dim s
Randomize
s = Rnd * 100
Dim conn, cmd
Set conn = Server.CreateObject("ADODB.Connection")
Set cmd = Server.CreateObject("ADODB.Command")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("sp.mdb")
With cmd
.ActiveConnection = conn
.CommandType = &H0004 '存储过程
.CommandText = "AddNewData"
End With
cmd.Execute , Array(CStr(Now()), CSng(s))
With cmd
.ActiveConnection = conn
.CommandType = &H0004 '存储过程
.CommandText = "GetData"
End With
Dim resultRS, resultArray
Set resultRS = cmd.Execute(, Null)
If Not resultRS.EOF Then
resultArray = resultRS.GetRows()
End If
Set resultRS = Nothing
Set cmd = Nothing
conn.Close
Set conn = Nothing
Response.Write "<ul>"
Dim i
For i = 0 To UBound(resultArray, 2)
Response.Write "<li>" & resultArray(0, i)
Response.Write " " & resultArray(1, i)
Response.Write " " & resultArray(2, i)
Response.Write "</li>"
Next
Response.Write "</ul>"
%>