VB中将ACCESSFlexGird和DataGrid中数据快速导出至EXCEL_把excel导入access
本文摘要: VB中将ACCESSFlexGird和DataGrid中数据快速导出至EXCEL_把excel导入access,Excel是一个非常优秀的报表制作软件,用VBA可以控制其生成优秀的报表,本文通过添加查询语句的方法,即用Excel中的获取外部数据的功能将数据很快地从一个查询语句中捕获到EXCEL中,比起往每个CELL里写数据的方法提高许多倍。一、将ACCESS表中的数据导出至EXCEL:将下文加入到一个模块中,

 Excel 是一个非常优秀的报表制作软件,用VBA可以控制其生成优秀的报表,本文通过添加查询语句的方法,即用Excel中的获取外部数据的功能将数据很快地从一个查询语句中捕获到EXCEL中,比起往每个CELL里写数据的方法提高许多倍。

一、将ACCESS表中的数据导出至EXCEL:

将下文加入到一个模块中,屏幕中调用如下ExporToExcel("select * from table")则实现将其导出到EXCEL中

添加一按钮,双击后输入:
Private Sub Command1_Click()
'导出至excel
    ExporToExcel ("select * from People")
End Sub

以下为函数主体内容(由孟子E章提供源代码,稍有改动,下文中注明改动地方及原因)

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 xlApp As New Excel.Application
    Dim xlBook As Excel.Workbook
    Dim xlSheet As Excel.Worksheet
    Dim xlQuery As Excel.QueryTable
    '这里增加ACCESS表连接内容,建立CONN连接对象,by boyd
    Dim data As String
    Dim strpath As String
    strpath = App.Path
    If Right(strpath, 1) <> "/" Then
    strpath = strpath & "/"
    End If
    strpath = strpath & "/MySmsBook.mdb"
    Set conn = New ADODB.Connection
    conn.Open "driver={Microsoft Access Driver (*.mdb)};pwd=;dbq=" & strpath
   
    With Rs_Data
        If .state = adStateOpen Then
            .Close
        End If
        .ActiveConnection = conn
        .CursorLocation = adUseClient
        .CursorType = adOpenStatic
        .LockType = adLockReadOnly
        .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表格程序为可视,去掉,by boyd
   
    '添加查询语句,导入EXCEL数据
    Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))
   
    With xlQuery
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = True
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
    End With
   
    xlQuery.FieldNames = True '显示字段名
    xlQuery.Refresh
   
    With xlSheet
        .Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Name = "黑体"
        '设标题为黑体字
        .Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Bold = True
        '标题字体加粗
        .Range(.Cells(1, 1), .Cells(Irowcount + 1, Icolcount)).Borders.LineStyle = xlContinuous
        '设表格边框样式
    End With
   
    With xlSheet.PageSetup
        .LeftHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10公司名称:"   ' & Gsmc
        .CenterHeader = "&""楷体_GB2312,常规""公司人员情况表&""宋体,常规""" & Chr(10) & "&""楷体_GB2312,常规""&10日 期:"
        .RightHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10单位:"
        .LeftFooter = "&""楷体_GB2312,常规""&10制表人:"
        .CenterFooter = "&""楷体_GB2312,常规""&10制表日期:"
        .RightFooter = "&""楷体_GB2312,常规""&10第&P页 共&N页"
    End With
    
    xlBook.SaveAs (App.Path & "\test.xls")    '增加保存设置,导出为文件,by boyd
    xlApp.Application.Visible = True
    Set xlApp = Nothing  '"交还控制给Excel
    Set xlBook = Nothing
    Set xlSheet = Nothing

End Function

注:须在程序中引用'Microsoft Excel 11.0 Object Library(如果是2000版本则是引用Microsoft Excel 9.0 Object Library)和ADO(Microsoft ActiveX Data Objects 2.6 Library)对象,机器必装Excel 2000或更高版的程序。

本程序在Windows 98/2000,VB 6 下运行通过。

二、将FlexGrid中的数据导出至EXCEL方法:

'*********************************************************
'*     名称:OutDataToExcel
'*     功能:将MsFlexGrid控件中显示的内容输出到Excel表格中进行打印
'*********************************************************
Public Sub OutDataToExcel(Flex As MSFlexGrid)                                 '导出至Excel
    On Error GoTo Ert
    Dim s         As String
    Dim i         As Integer
    Dim j         As Integer
    Dim k         As Integer
    Me.MousePointer = 11
    Dim Excelapp         As Excel.Application
    Set Excelapp = New Excel.Application
    On Error Resume Next
    DoEvents
    Excelapp.SheetsInNewWorkbook = 1
    Excelapp.Workbooks.Add
    Excelapp.ActiveSheet.Cells(1, 3) = s
    Excelapp.Range("C1").Select
    Excelapp.Selection.Font.FontStyle = "Bold"
    Excelapp.Selection.Font.Size = 16
    With Flex
        k = .Rows
        For i = 0 To k - 1
            For j = 0 To .Cols - 1
                DoEvents
                Excelapp.ActiveSheet.Cells(3 + i, j + 1) = "'" & .TextMatrix(i, j)
            Next j
        Next i
    End With
    Me.MousePointer = 0
    Excelapp.Visible = True
    Excelapp.Sheets.PrintPreview
Ert:
    If Not (Excelapp Is Nothing) Then
        Excelapp.Quit
    End If
End Sub

三、将DataGrid中的数据导出至EXCEL方法:

在FORM的LOAD事件中加入:  
    Data1.DatabaseName   =   数据库名称  
    Data1.RecordSource   =   表名  
    Data1.Refresh  
   
  在按钮的CLICK事件中加入  
    Dim   Irow,   Icol   As   Integer  
    Dim   Irowcount,   Icolcount   As   Integer  
    Dim   Fieldlen()   "存字段长度值  
    Dim   xlApp   As   Excel.Application  
    Dim   xlBook   As   Excel.Workbook  
    Dim   xlSheet   As   Excel.Worksheet  
   
    Set   xlApp   =   CreateObject("Excel.Application")  
    Set   xlBook   =   xlApp.Workbooks.Add  
    Set   xlSheet   =   xlBook.Worksheets(1)  
   
    With   Data1.Recordset  
    .MoveLast  
   
    If   .RecordCount   <   1   Then  
      MsgBox   ("Error   没有记录!")  
      Exit   Sub  
    End   If  
   
    Irowcount   =   .RecordCount   "记录总数  
    Icolcount   =   .Fields.Count   "字段总数  
   
    ReDim   Fieldlen(Icolcount)  
    .MoveFirst  
   
   
   
    For   Irow   =   1   To   Irowcount   +   1  
     For   Icol   =   1   To   Icolcount  
    Select   Case   Irow  
    Case   1   "在Excel中的第一行加标题  
    xlSheet.Cells(Irow,   Icol).Value   =   .Fields(Icol   -   1).Name  
    Case   2   "将数组FIELDLEN()存为第一条记录的字段长  
   
    If   IsNull(.Fields(Icol   -   1))   =   True   Then  
      Fieldlen(Icol)   =   LenB(.Fields(Icol   -   1).Name)  
       "如果字段值为NULL,则将数组Filelen(Icol)的值设为标题名的宽度  
    Else  
      Fieldlen(Icol)   =   LenB(.Fields(Icol   -   1))  
    End   If  
   
    xlSheet.Columns(Icol).ColumnWidth   =   Fieldlen(Icol)  
     "Excel列宽等于字段长  
    xlSheet.Cells(Irow,   Icol).Value   =   .Fields(Icol   -   1)  
     "向Excel的CellS中写入字段值  
    Case   Else  
    Fieldlen1   =   LenB(.Fields(Icol   -   1))  
   
    If   Fieldlen(Icol)   <   Fieldlen1   Then  
    xlSheet.Columns(Icol).ColumnWidth   =   Fieldlen1  
     "表格列宽等于较长字段长  
    Fieldlen(Icol)   =   Fieldlen1  
     "数组Fieldlen(Icol)中存放最大字段长度值  
    Else  
     xlSheet.Columns(Icol).ColumnWidth   =   Fieldlen(Icol)  
    End   If  
   
    xlSheet.Cells(Irow,   Icol).Value   =   .Fields(Icol   -   1)  
    End   Select  
    Next  
    If   Irow   <>   1   Then  
    If   Not   .EOF   Then   .MoveNext  
    End   If  
    Next  
    With   xlSheet  
    .Range(.Cells(1,   1),   .Cells(1,   Icol   -   1)).Font.Name   =   "黑体"  
     "设标题为黑体字  
    .Range(.Cells(1,   1),   .Cells(1,   Icol   -   1)).Font.Bold   =   True  
     "标题字体加粗  
    .Range(.Cells(1,   1),   .Cells(Irow,   Icol   -   1)).Borders.LineStyle   =   xlContinuous  
     "设表格边框样式  
    End   With  
    xlApp.Visible   =   True   "显示表格  
    xlBook.Save   "保存  
    Set   xlApp   =   Nothing   "交还控制给Excel  
    End   With