vb datagrid 导出excel

来源:百度知道 编辑:UC知道 时间:2024/06/10 02:38:51
Dim i As Integer
Dim j As Integer
Dim xlApp As New Excel.Application
Dim xlBook As New Excel.Workbook
Dim xlSheet As New Excel.Worksheet
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlBook = xlApp.Workbooks.Add
On Error Resume Next
Set xlBook = xlApp.Workbooks.Open("d:\text2.xls")
Set xlSheet = xlBook.Worksheets(1)
For j = 0 To DataGrid1.Columns.Count - 1
xlSheet.Cells(1, j + 1) = DataGrid1.Columns.Item(j).Caption
Next j
xlSheet.Cells(6, 1) = "i"
Adodc1.Recordset.MoveFirst
For i = 0 To Adodc1.Recordset.RecordCount - 1
DataGrid1.Row = i
For j = 0 To DataGrid1.Columns.Count - 1
DataGrid1.Col = j
'MsgBox DataGrid1.Text

If IsNull(DataGrid1.Text) = False Then
xlSheet.Cells(i + 2, j + 1) = DataGrid1.Text
End If
Next j
Next i<

adodc1.recordset.MoveFirst
for i = 0 to adodc1.recordset.recordcount - 1
'For j = 0 To DataGrid1.Columns.Count - 1 '这一行跟下一行效果一样
For j = 0 To adodc1.recordset.fields.Count - 1
xlSheet.Cells(i + 1, j + 1) = adodc1.recordset(j)
Next j
adodc1.recordset.movenext
next i

你不要从DATAGRid1里导出。而是要从记录集里导出。
for i=1 to adodc1.recordset.recordcount
xlSheet.Cells(i + 2, j + 1) = adodc1.recordset(1)'这是第一列的数据
xlSheet.Cells(i + 2, j + 1) = adodc1.recordset(2)'这是第2列的数据
xlSheet.Cells(i + 2, j + 1) = adodc1.recordset(...)'这是第...列的数据
xlSheet.Cells(i + 2, j + 1) = adodc1.recordset(n)'这是第n列的数据
adodc1.recordset.movenext
next