网络编程
位置:首页>> 网络编程>> Asp编程>> 如何将数据库里的记录生成一个Excel文件?

如何将数据库里的记录生成一个Excel文件?

 来源:asp之家 发布时间:2009-12-03 20:09:00 

标签:excel,数据库,生成

我想把存在数据库里的每天24小时来访者数另放到一个Excel文件中去,可以吗?

可以,其实就是将数据库里面的内容生成一个Excel文件:

toexcel.asp


<%@ LANGUAGE="VBSCRIPT" %>
<%option explicit%>
<HTML>
<HEAD>
<meta content="text/html; charset=gb2312" http-equiv="Content-Type">
<TITLE>asp教程之生成Excel文件 - Aspxhome.com</TITLE>
</HEAD>
<body>
<a href="dbtoexcel.asp?act=make">网站来访者人数之Excel报告</a>
<hr size=1 align=left width=300px>
<%
if Request("act") = "" then
else
  dim conn
  set conn=server.CreateObject("adodb.connection")
  conn.Open "test","sa",""
  'conn.Open Application("connstr")
  dim rs,sql,filename,fs,myfile,x,link
  
  Set fs = server.CreateObject("scripting.filesystemobject")
  filename = "c:\visitintels.xls"
  ' 生成的Excel文件路径
  if fs.FileExists(filename) then
    fs.DeleteFile(filename)
  ' 如有原来相同的Excel文件删除(覆盖)它
  end if
  set myfile = fs.CreateTextFile(filename,true)
  ' 创建Excel文件

  Set rs = Server.CreateObject("ADODB.Recordset")
  sql = "select population,hourpos,datepos from populationperhour order by datepos,hourpos asc"
  ' 从数据库中把需放到Excel文件中的数据查找出来
  rs.Open sql,conn
  if rs.EOF and rs.BOF then
  
  else
  
    dim strLine,responsestr
    strLine=""
      For each x in rs.fields
        strLine= strLine & x.name & chr(9)
      Next
    
      '--将表的列名先写入EXCEL
      myfile.writeline strLine
      Do while Not rs.EOF
      strLine=""
    
      for each x in rs.Fields
        strLine= strLine & x.value & chr(9)
      next
      myfile.writeline strLine
' 将表的数据写入Excel文件
      rs.MoveNext
      loop
      
  end if
rs.Close
set rs = nothing
conn.close
set conn = nothing
set myfile = nothing
Set fs=Nothing
link="<A HREF=" & filename & ">Open The Excel File</a>"
Response.write link
end if
%>
</BODY>
</HTML>

下面是数据库的内容:

CREATE TABLE [populationperhour] (
    [population] [int] NOT NULL ,
    [hourpos] [int] NOT NULL ,
    [datepos] [datetime] NOT NULL 
);
insert into populationperhour values('135','1','2001-10-17');
insert into populationperhour values('667','2','2001-10-17');
insert into populationperhour values('557','3','2001-10-17');
...
insert into populationperhour values('167','660','2001-10-17');
insert into populationperhour values('843','661','2001-10-17');

 

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com