首先建立一个Excel模板。在本示例是在同一目录下新建一个excel文件。
Excel模板如下图:

以下是ASP利用Excel模板生成Excel报表源代码:
<%
'测试时把这一句注释掉才可以看到出错信息
On Error Resume Next
Dim Fso,TempFile,TargetFile,TargetFileName
'报表的文件名
TargetFileName = Year(Now)&Month(Now)&Day(Now)&Hour(Now)&Minute(Now)&Second(Now)
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
'模板的路径
TempFile = Server.MapPath("template.xls")
'目标文件的路径
TargetFile = Server.MapPath(TargetFileName&".xls")
'检测模板文件
If Fso.FileExists(TempFile) Then
'模板存在
'按模板创建新报表并修改新报表
Fso.CopyFile TempFile,TargetFile,True
CreateExcel()
Else
'模板不存在
Response.Write("模版文件不存在!")
End If
Set Fso = Nothing
'====================================================
'Title:报表的表头
'strDate:日期
'strTo:目标
'From:来源
'Attn:
'Name:
'Fax1:传真1
'Fax2:传真2
'其他变量自己添加
'====================================================
Function CreateExcel()
Dim Title,strDate,strTo,From,Attn,Name,Fax1,Fax2
Dim xlsApp
Dim workBooks,xlsWorkSheet
if IsObjInstalled("Excel.Application") = False then
response.Write("<script>alert('创建Excel.Application失败!');history.back()</script>")
response.End()
end if
'创建Excel对象
Set xlsApp = Server.CreateObject("Excel.Application")
Set workBooks = xlsApp.workbooks.Open(TargetFile)
workBooks.windows.Application.DisplayAlerts = False
workBooks.windows.Application.Visible = False
workBooks.Activate
Set xlsWorkSheet = workBooks.workSheets(1)
'设置变量,可以从数据库里读出
Title = "Title"
strDate = Now()
strTo = "ToWho"
From = "FromWho"
Attn = "Attn"
Name = "Name"
Fax1 = "Fax1"
Fax2 = "Fax2"
'----------------------------------------------
'开始修改模板
'----------------------------------------------
xlsWorkSheet.Range("A1").Value = Title
xlsWorkSheet.Range("E2").Value = strDate
xlsWorkSheet.Range("B3").Value = strTo
xlsWorkSheet.Range("E3").Value = From
xlsWorkSheet.Range("B4").Value = Attn
xlsWorkSheet.Range("E4").Value = Name
xlsWorkSheet.Range("B5").Value = Fax1
xlsWorkSheet.Range("E5").Value = Fax2
xlsApp.Save
'-----------------------------------------------
'修改完成并保存
'-----------------------------------------------
'释放对象
workBooks.Application.Quit
xlsApp.Quit
Set xlsWorkSheet = Nothing
Set workBooks = Nothing
Set xlsApp = Nothing
Response.Write("<a href='"&TargetFileName&".xls'>报表已经生成,点击查看</a>")
End Function
Function IsObjInstalled(strClassString)
On Error Resume Next
IsObjInstalled = False
Err = 0
Dim xTestObj
Set xTestObj = Server.CreateObject(strClassString)
If Err = 0 Then IsObjInstalled = True
Set xTestObj = Nothing
Err = 0
End Function
%>
这时当运行该代码时可能出现如下的错误信息:
错误类型:
Server 对象, ASP 0178 (0x80070005)
检查权限时,对 Server.CreateObject 的调用失败。拒绝对此对象的访问。
这是因为IIS没有权限调用Excel的缘故。
解决办法:
开始-运行dcomcnfg.exe,组件服务-> 计算机-> 我的电脑-> dcom配置,找到Microsoft Excel 应用程序项,配置Excel的“安全性”-> 默认访问权限、默认启动权限、默认配置权限都设置为“自定义”,并在可访问用户中添加上IUSR_的帐号就OK啦
我使用您的程式跟操作,最後出現.請問還有那裡要修改.
Microsoft Office Excel 錯誤 '800a03ec'
無法取用唯讀檔案 'RESUME.XLW'。
/toexcel-1.asp, 列72