因?yàn)楝F(xiàn)在在做個(gè)項(xiàng)目,客戶要求能將Excel里的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫(kù)中(sql 2000)(,在網(wǎng)上搜索了很久,都沒(méi)有詳細(xì)點(diǎn)的,經(jīng)過(guò)修改后,終于實(shí)現(xiàn)了這功能,特發(fā)出來(lái)供有需要的朋友參考.
將Excel中的數(shù)據(jù)導(dǎo)入到sql 2000(Access)中,前提是在sql 2000(Access)中的表已經(jīng)建好。
有兩個(gè)文件,excel.htm,excelTosql.asp
excel.htm用于建立個(gè)表單頁(yè)面,讓用戶選擇文件來(lái)源.代碼如下:
以下是excel.htm代碼:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無(wú)標(biāo)題文檔</title>
</head>
<body>
<form action="excelTosql.asp" method="post" name="form1" id="form1">
<p>
<input name="bbb" type="file" id="bbb" size="30" />
</p>
<p>
<input type="submit" name="Submit" value="提交" />
</p>
</form>
</body>
</html> |
excelTosql.asp:用于處理表單提交過(guò)來(lái)的數(shù)據(jù)(顯示并寫入數(shù)據(jù)庫(kù)),代碼如下:
以下是excelTosql.asp代碼片段:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<%'sql 連接驅(qū)動(dòng)
dim conn,connstr,time1,time2,mdb
time1=timer
'如果是sql 2000數(shù)據(jù)庫(kù),請(qǐng)用下面 連接驅(qū)動(dòng)
connstr = "Driver={SQL Server};server=(local);uid=sa;pwd=123;database=jmgl2007;"
'如果是Access數(shù)據(jù)庫(kù),請(qǐng)用下面 連接驅(qū)動(dòng)
'connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(mdb/jmgl2007.mdb)
Set conn = Server.Createobject("ADODB.Connection")
conn.Open connstr
If Err Then
err.Clear
Set Conn = Nothing
Response.Write "數(shù)據(jù)庫(kù)連接出錯(cuò),請(qǐng)檢查連接字串。"
Response.End
End If
sub closedb()
conn.close
set conn=nothing
end sub
dim aa
aa=request.form("bbb") '獲取傳遞過(guò)來(lái)的值
Dim StrConnect,cc
Dim objConn
Dim rs
Dim Sql
cc=0
'Excel連接驅(qū)動(dòng)
aaa="provider=Microsoft.Jet.OLEDB.4.0; Data Source="&aa&";Extended Properties='Excel 8.0;HDR=yes;IMEX=1'"
set StrConnect=CreateObject("ADODB.Connection")
StrConnect.Open aaa
Set objConn=CreateObject("ADODB.Connection")
objConn.Open StrConnect
'注意 表名一定要以下邊這種格試 "[表名$]" 書寫
Set rs = Server.CreateObject("ADODB.Recordset")
Sql="select * from [sheet1$] "
rs.Open Sql,StrConnect,2,2
IF rs.Eof And Rs.Bof Then
response.Write("<script>alert ('沒(méi)有資料可以導(dǎo)入!');history.go(-1)</script>")
else
Do While Not rs.EOF
'列出表內(nèi)信息
response.write"excel數(shù)據(jù)為: <br>"
response.write ""&rs(0)&"-"&rs(1)&"-"&rs(2)&""
response.write"<br>"
set rssql=server.CreateObject("adodb.recordset")
'插入SQL2000里
rssql.Open "select * from abc",conn,1,3
rssql.AddNew
if rs(0)<>"" then
rssql(1)=rs(0)
end if
if rs(1)<>"" then
rssql(2)=rs(1)
end if
if rs(2)<>"" then
rssql(3)=rs(2)
end if
rssql.Update
Rs.MoveNext
Loop
end if
response.Write "<script language=javascript>alert('資料導(dǎo)入成功!\n共有"&cc&"條數(shù)據(jù)導(dǎo)入');history.go(-1)</script>"
%> |
該文章在 2010/11/18 20:41:03 編輯過(guò)