how to use asp to operate mssql

1 读取Excel文件
<%
set xlApp = server.CreateObject("Excel.Application")
strsource = server.MapPath("xl.xls")
set xlbook = xlApp.WorkBooks.Open(strsource)
set xlsheet = xlbook.Worksheets(1)

i = 1
response.write "<table>"

while xlsheet.cells(i,1) <> ""

   response.write "<tr>"
   response.write "<td>" & xlsheet.Cells(i,1) & "</td>"
   response.write "<td>" & xlsheet.Cells(i,2) & "</td>"
   response.write "<td>" & xlsheet.Cells(i,3) & "</td>"
   response.write "<tr>"
   i = i + 1
  
wend

response.write "</table>"
set xlsheet = nothing
set xlbook  = nothing
xlApp.quit
'千万记住要加这一句,否则每运行一次你的机器里就增加一个Excel进程,而且无法释放
'set xlApp = nothing 是不行的
%>
================================================================
2. Excel导入到SQL Server中
<%
sub dataIntoSqlServer_ceritificate(strFileName,strSheetName,myConn)
   '定义
   dim myConnection
   dim strName
   dim rsXsl,rsSql
   dim myConn_Xsl
   dim cmd
   dim i,j
   dim maxId
  
   strName = strFileName
   set myConnection = Server.CreateObject("ADODB.Connection")
   set rsXsl = Server.CreateObject("ADODB.Recordset")
   set rsSql = Server.CreateObject("ADODB.Recordset")
   set cmd   = server.CreateObject("ADODB.Command")
  
   cmd.ActiveConnection = myConn
  
   myConn_Xsl = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strName & _
               ";Extended Properties=Excel 8.0"
   '打开连接
    myconnection.open myConn_Xsl
   '打开表     
   str_Xsl = "select * from [" & strSheetName & "$]"
   rsXsl.open str_Xsl,myconnection,1,1
   j = 1
   Do while not rsXsl.eof
   '取出最大值
   str_sql = "select Max(id) as maxId from exceltosql"
   rsSql.open str_Sql,myConn,1,3
   if Not rsSql.eof then
      if not isNull(rsSql("maxId")) then
         maxId=CLng(rsSql("maxId")) + 1
      else
         maxId = 1
      end if
   else
      maxId = 1
   end if
   rsSql.close   '//关闭对象
   '加入数据库
   str_Sql = "insert into exceltosql values(" & maxId&",'"&rsXsl(1)&"','" & rsXsl(2)&"')"
      cmd.CommandText = str_Sql
      cmd.Excute()
      ''''''''''''''''''''''''''''''''''''''''''
      j = j + 1
      rsXsl.moveNext
   loop
  
   response.write "共导入 " & j_1 & " 条记录.<br>"
   response.write "<a href=# onclick='self.close();'>关闭窗口</a>"
   set rsXsl = nothing
   set rsSql = nothing
   set myconnection = nothing
   set cmd = nothing
end sub


(2)
'调用方法
<%
file1 = "c:\excelexample.xls"
myconn = "DRIVER={SQL SERVER};SERVER=(local);uid=sa;pwd=sa;DATABASE=aspbook"
dataIntoSqlServer_ceritificate file1,"sheet1",myconn
%>

你可能感兴趣的:(sql,SQL Server,Excel,asp,XSL)