一直以来,好象提到将DataGrid的数据导出到EXCEL里面的办法都直接涉及数据源,也就是DataGrid的数据来源,具体说就是数据库的数据表,于是我希望能直接导出DataGrid的数据:
Private Sub Command2_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 = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
For k = 0 To DataGrid1.Columns.Count - 1 'DataGrid所有的列数
xlSheet.Cells(1, k + 1) = DataGrid1.Columns(k).Caption '第一行为DataGrid的列标题
NextFor i = 0 To DataGrid1.ApproxCount - 1 'DataGrid的所有行数
DataGrid1.Row = i
For j = 0 To DataGrid1.Columns.Count - 1 'DataGrid所有的列数,若将此数改小到不拉DataGrid的垂直滚动条的时候能看见的行数的时候正常
DataGrid1.Col = j
xlSheet.Cells(i + 2, j + 1) = DataGrid1.Text '从第二行显示'DataGrid的内容
Next
Next
Set xlApp = Nothing '交还控制给Excel
Set xlBook = Nothing
Set xlSheet = Nothing
End Sub但有一个奇怪的现象,当不拉DataGrid的垂直滚动条的时候能看见的行数可以正常导出,但不拉DataGrid的垂直滚动条的时候能看不见的行数不正常.具体情况是:从看不见的行开始,导出的内容跨了一行,再下面,跨了两行……
1
2
3
4
5
6
7
8
10
13
17
22
28
35
43
52
62
73
85
98
这为导出的行数,而DataGrid里面的数据是连续的。
这到底是DataGrid本身的问题还是程序设计的问题?
请指点!
我希望不涉及数据源,DataGrid是什么就导出什么.
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 = CreateObject("Excel.Application")
'xlApp.Visible = True
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.Row = 0For 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) = DataGrid1.Text '从第二行显示'DataGrid的内容
Next
If i < DataGrid1.ApproxCount - 1 Then
DataGrid1.Row = DataGrid1.Row + 1
End If
Next
Me.MousePointer = 0
MsgBox "ok"
xlApp.Visible = True
Set xlApp = Nothing '交还控制给Excel
Set xlBook = Nothing
Set xlSheet = Nothing
End SubPrivate Sub Form_Load()
MsgBox Adodc1.Recordset.RecordCount
MsgBox DataGrid1.ApproxCount
End Sub
DataGrid1.Row = 0
好象不起控制作用.
假设导出前拉动过垂直滚动条,结果就会出错.
DataGrid1.Row = 0问题解决!