日期:2013-01-27  浏览次数:20714 次

一个用组件动态创建Excel文件的实例

   在精华区中有一篇关于在ASP中动态创建的Excel文章, 但实际上我们会发现如果我们在ASP中用Set MyExcelChart = server.CreateObject("Excel.Sheet")是行不通的. 这样做的话会出现如下的错误信息:
Only InProc server components should be used. If you want to use LocalServer components, you must set the AspAllowOutOfProcComponents metabase setting. Please consult the help file for important considerations关于此出错信息的详细内容你可以看:
http://msdn.microsoft.com/workshop/server/components/outproc.asp
所以, 要想在服务器自动生成Excel文件还是必须通过组件来实现(个人意见,如果你有更好的方法请告诉我:-)).
设计环境:VB6.0
运行环境:NT4.0(sp5)+IIS4.0+MTS
1.新建一个DLL工程.工程名为p_excel,类名为c_excel
2.在"project"->"references"中选中"Microsoft Excel 9 Object Library".
3.代码
Option Explicit

Dim oExcel As Excel.Application
Dim oSheet As Excel.Worksheet
Dim oTitle As Excel.Range

Public Sub CreateExcel()
    Set oExcel = New Excel.Application
    oExcel.Visible = False
    oExcel.Workbooks.Add
    Set oSheet = oExcel.Workbooks(1).Worksheets("Sheet1")
    oSheet.Activate
    Set oTitle = oSheet.Range("A1")
    oTitle.Value = "Excel Title"
    oTitle.Font.Bold = -1
    oTitle.Font.Size = 18
    oTitle.Font.Name = "Arial"
    oSheet.SaveAs "allen.xls"
    oExcel.Quit
    Set oExcel = Nothing
End Sub
4.编译生成p_excel.dll
5.使用MTS注册p_excel.dll
6.ASP文件代码并在IIS中设置要生成excel文件的虚拟目录对用户有写的权限.
excel.asp
<%
set myExcel=server.createobject("p_excel.c_excel")
myExcel.CreateExcel
set myExcel=nothing
%>
7.运行excel.asp,在相关目录下我们就可以找到生成的Excel文件.

改进的建议:
1.在p_excel.dll中增加(range,value)的属性就可以利用从数据库中查询返回的记录动态生成Excel文档.
2.增加Email功能自动将生成的Excel文件发送给相关用户.

如果你还有其他的建议请告诉我:-)