vb6的导出到Excel的函数
Private Sub Command1_Click()
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
xlSheet.Columns.AutoFit
Me.MousePointer = 11
For k = 0 To DataGrid1.Columns.Count - 1 'DataGrid所有的列数
xlSheet.Cells(1, k + 1) = DataGrid1.Columns(k).Caption '第一行为DataGrid的列标题
Next
DataGrid1.Scroll 0, -DataGrid1.FirstRow '导出前拉动过垂直滚动条,这个非常重要
DataGrid1.Row = 0
For i = 0 To DataGrid1.ApproxCount - 1 'DataGrid的所有行数
For j = 0 To DataGrid1.Columns.Count - 1 'DataGrid所有的列数,若将此数改小到不拉DataGrid的垂直滚动条的时候能看见的行数的时候正常
DataGrid1.Col = j
xlSheet.Cells(i + 2, j + 1) = Adodc1.Recordset(j) 'DataGrid1.Text '从第二行显示'DataGrid的内容
Next
If i < DataGrid1.ApproxCount - 1 Then
DataGrid1.Row = DataGrid1.Row + 1
End If
Next
Me.MousePointer = 0
MsgBox "导出成功!"
xlApp.Visible = True
Set xlApp = Nothing 'Excel 处于当前窗体
Set xlBook = Nothing
Set xlSheet = Nothing
End Sub