标签:
在Access和MSSqlserver里都有将表直接导出到Excel的工具,可是当客户需要在程序里将数据库里的表生成Excel表格时,我们用一般的T-sql语句很难做到!下面是我结合网上资料和客户的需求写的代码,仅供学习交流.
<%
set rs=server.CreateObject("adodb.recordset")
sql="select * from Stu_signUp order by id asc"
rs.open sql,conn,1,1
Set fs = server.CreateObject("scripting.filesystemobject")
‘--假设你想让生成的EXCEL文件做如下的存放
filename = Server.MapPath("users.xls")
‘--如果原来的EXCEL文件存在的话删除它
if fs.FileExists(filename) then
fs.DeleteFile(filename)
end if
‘--创建EXCEL文件
set myfile = fs.CreateTextFile(filename,true)
dim ttxt,file,filepath,writefile
ttxt="user.xls" ‘为要写入的文件取个文件名,后缀可以是txt,xls,这里我用csv,这种文件打开也是excel表
Set file = CreateObject("Scripting.FileSystemObject")
Application.lock ‘写入文件的存放路径,一定要开放这个路径下的读写权限
filepath=Server.MapPath(ttxt)
Set Writefile = file.CreateTextFile(filepath,true)
‘在表格中写入第一行,字段描述,这个根据你实际的数据表字段来写
if not (rs.eof And rs.bof) then
dim trLine,responsestr
strLine=""
‘如果你不需要改边列名
For each x in rs.Fields
strLine=strLine &x.name& chr(9)
next
‘如果你的数据表中的字段非用户想要看到的,在这里可以将你的字段放在数组中写在Excel的首行
arr=array("编号","学生姓名","学生性别","生日","所在学校","年级","班级","英语启蒙年龄","是否在课外机构学习英语","课外机构名称","入学时间","家长姓名","家长称谓","家长手机","家长工作单位","家长职业","学历","报名日期")
For i=0 to Ubound(arr)
strLine = strLine & arr(i)& chr(9)
Next
myfile.writeline strLine
Do while Not rs.EOF
strLine=""
j=0
for each x in rs.Fields
strLine = strLine &x.value& chr(9)
next
myfile.writeline strLine
rs.MoveNext
loop
myfile.close
rs.close
set rs=nothing
end if
‘完成写入
%>
在Access和MSSqlserver里都有将表直接导出到Excel的工具
标签:
原文地址:http://www.cnblogs.com/keringing/p/5932208.html