由于工作的需要,我需要为客户做一个在线生成Excel及Word报表程序,参考了网上很多办法
大多数都是采用Excel.Application(
http://www.blueidea.com/tech/program/2006/3547.asp)组件来生成
发现容易出错,而且对于大多数和我一样的菜鸟来说,比较麻烦,考虑到前些天用ASP+模板+adodb.stream生成静态页面的办法,经过多次尝试,终于掌握了一种用ASP+模板生成Excel和word的新的办法,先分享如下:
用模板生成Excel、Word最大优点:
Word、Excel文档样式易于控制和调整,以往用Excel.Application来生成Excel、Word,需要写很多代码来控制排版的样式,用模版几乎不受任何限制,只需要打开word或Excel,编辑文档,选择"文件->另存为web页",即可方便的做好模板 ,用office生成的模板要比直接在DW中做好模板更加符合office偏好,生成后文件样式可与原word、Excel格式99%一样,因此建议大家用office(office97~office2003)直接来生成模板框架。
主要的代码
function.asp
复制代码 代码如下:
生成Excel文档: 复制代码 代码如下:
<%
'创建文件
dim templateName,templatechar,filepath,filename,fileCharset,templateContent
templateName="template/template_excel.htm" '模板名字,支持带路径,如"/moban/moban1.htm"或"temp/moban1.htm"
templatechar="gb2312" '模板文本的编码
filepath="files/excel/" '生成文件保存的路径,当前目录请留空,其他目录,路径必须以“/”结尾
filename="Book1.xls" '即将生成的文件名
CreateMultiFolder(filepath) '这一句用来判断文件夹是否存在,没有则自动创建,支持n级目录
fileCharset="gb2312" '打算生成的文本编码
'读取指定的模板内容
templateContent=ReadFromTextFile(templateName,templatechar)
'以下就交给你来替换模板内容了
templateContent=replace(templateContent,"{$websiteName}","蓝色理想")
templateContent=replace(templateContent,"{$userName}","幸福的子弹")
templateContent=replace(templateContent,"{$now}",Now())
'其他内容......
'最终调用函数来生成文件
Call WriteToTextFile(filepath&filename,templateContent,fileCharset)
'最后关闭adodb.stream对象
stm.flush
stm.Close
set stm=nothing
downloadFile(filepath&filename)
%>
生成.htm静态页面 复制代码 代码如下:
<%
'创建文件
dim templateName,templatechar,filepath,filename,fileCharset,templateContent
templateName="template/template_html.htm" '模板名字,支持带路径,如"/moban/moban1.htm"或"temp/moban1.htm"
templatechar="gb2312" '模板文本的编码
filepath="files/html/" '生成文件保存的路径,当前目录请留空,其他目录,路径必须以“/”结尾
filename="Untitled-1.htm" '即将生成的文件名
CreateMultiFolder(filepath) '这一句用来判断文件夹是否存在,没有则自动创建,支持n级目录
fileCharset="gb2312" '打算生成的文本编码
'读取指定的模板内容
templateContent=ReadFromTextFile(templateName,templatechar)
'以下就交给你来替换模板内容了
templateContent=replace(templateContent,"{$websiteName}","蓝色理想")
templateContent=replace(templateContent,"{$userName}","幸福的子弹")
templateContent=replace(templateContent,"{$now}",now())
'其他内容......
'最终调用函数来生成文件
Call WriteToTextFile(filepath&filename,templateContent,fileCharset)
'最后关闭adodb.stream对象
stm.flush
stm.Close
set stm=nothing
response.Write("恭喜您,"&filename&"已经生成,<a href="""&filepath&filename&""" target=""_blank"">点击查看</a>")
%>
打包文件下载