如何将记录集的数据一次性导出至excel。
注意:1、不要用循环逐条导出。
      2、不要用 select into 语句。

解决方案 »

  1.   

    '导出记录集数据到Excel
    '你设置好 strOpen 查询语句就可以了
    Public Function ExporToExcel(strOpen As String)
    '*********************************************************
    '* 名称:ExporToExcel
    '* 功能:导出数据到EXCEL
    '* 用法:ExporToExcel(sql查询字符串)
    '*********************************************************
        Dim Rs_Data As New ADODB.Recordset
        Dim Irowcount As Integer
        Dim Icolcount As Integer
        Dim cn As New ADODB.Connection
        Dim xlapp As New Excel.Application
        Dim xlbook As Excel.Workbook
        Dim xlsheet As Excel.Worksheet
        Dim xlQuery As Excel.QueryTable
        With Rs_Data
            If .State = adStateOpen Then
                .Close
            End If
            .ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\db1.mdb"
            .CursorLocation = adUseClient
            .CursorType = adOpenStatic
            .Source = strOpen
            .Open
        End With
        With Rs_Data
            If .RecordCount < 1 Then
                MsgBox ("没有记录!")
                Exit Function
            End If
            '记录总数
            Irowcount = .RecordCount
            '字段总数
            Icolcount = .Fields.Count
        End With
        
        Set xlapp = CreateObject("Excel.Application")
        Set xlbook = Nothing
        Set xlsheet = Nothing
        Set xlbook = xlapp.Workbooks().Add
        Set xlsheet = xlbook.Worksheets("sheet1")
        xlapp.Visible = True
        
        '添加查询语句,导入EXCEL数据
        Set xlQuery = xlsheet.QueryTables.Add(Rs_Data, xlsheet.Range("a1"))
        
        xlQuery.FieldNames = True '显示字段名
        xlQuery.Refresh
        
        xlapp.Application.Visible = True
        Set xlapp = Nothing  '"交还控制给Excel
        Set xlbook = Nothing
        Set xlsheet = Nothing
        
    End Function
    需引用Microsoft Excel 9.0 Object Library