.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
在asp.net中使用excel模板

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

Imports System.Runtime.InteropServices.Marshal

Then, replace the default Page_Load event with the code in Figure 1.

Private Sub Page_Load(ByVal sender As System.Object, _

  ByVal e As System.EventArgs) Handles MyBase.Load

    Dim oExcel As New Excel.Application()

    Dim oBooks As Excel.Workbooks, oBook As Excel.Workbook

    Dim oSheets As Excel.Sheets, oSheet As Excel.Worksheet

    Dim oCells As Excel.Range

    Dim sFile As String, sTemplate As String

    Dim dt As DataTable = _

    CType(Application.Item("MyDataTable"), DataTable)

 

    sFile = Server.MapPath(Request.ApplicationPath) & _

      "\MyExcel.xls"

 

    sTemplate = Server.MapPath(Request.ApplicationPath) & _

       "\MyTemplate.xls"

 

    oExcel.Visible = False : oExcel.DisplayAlerts = False

 

    'Start a new workbook

    oBooks = oExcel.Workbooks

    oBooks.Open(Server.MapPath(Request.ApplicationPath) & _

    "\MyTemplate.xls") 'Load colorful template with chart

    oBook = oBooks.Item(1)

    oSheets = oBook.Worksheets

    oSheet = CType(oSheets.Item(1), Excel.Worksheet)

    oSheet.Name = "First Sheet"

    oCells = oSheet.Cells

 

    DumpData(dt, oCells) 'Fill in the data

 

    oSheet.SaveAs(sFile) 'Save in a temporary file

    oBook.Close()

 

    'Quit Excel and thoroughly deallocate everything

    oExcel.Quit()

    ReleaseComObject(oCells) : ReleaseComObject(oSheet)

    ReleaseComObject(oSheets) : ReleaseComObject(oBook)

    ReleaseComObject(oBooks) : ReleaseComObject(oExcel)

    oExcel = Nothing : oBooks = Nothing : oBook = Nothing

    oSheets = Nothing : oSheet = Nothing : oCells = Nothing

    System.GC.Collect()

    Response.Redirect(sFile) 'Send the user to the file

End Sub

 

'Outputs a DataTable to an Excel Worksheet

Private Function DumpData(ByVal _

  dt As DataTable, ByVal oCells As Excel.Range) As String

    Dim dr As DataRow, ary() As Object

    Dim iRow As Integer, iCol As Integer

 

    'Output Column Headers

    For iCol = 0 To dt.Columns.Count - 1

        oCells(2, iCol + 1) = dt.Columns(iCol).ToString

    Next

 

    'Output Data

    For iRow = 0 To dt.Rows.Count - 1

        dr = dt.Rows.Item(iRow)

        ary = dr.ItemArray

        For iCol = 0 To UBound(ary)

            oCells(iRow + 3, iCol + 1) = ary(iCol).ToString

            Response.Write(ary(iCol).ToString & vbTab)

        Next

    Next

End Function




相关文章

相关软件