Sub SaveasXls(MForm As Form, ByVal MRs As Recordset) On Error Resume Next Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Dim j, k As Integer '将对象引用赋值给这些变量。 '用 Add方法 创建新的工作簿和工作表对象。 MForm.CommonDialog1.FileName = "" MForm.CommonDialog1.ShowSave If MForm.CommonDialog1.FileName <> "" Then MRs.MoveFirst Set xlApp = New Excel.Application Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets.Item(1) For j = 0 To MRs.RecordCount For k = 0 To MRs.Fields.Count - 1 If j = 0 Then xlSheet.Cells(j + 1, k + 1) = MForm.DataGrid1.Columns(k).Caption Else xlSheet.Cells(j + 1, k + 1) = CStr(MRs.Fields(MForm.DataGrid1.Columns(k).DataField).Value) End If Next k If j <> 0 Then MRs.MoveNext Next j xlSheet.SaveAs MForm.CommonDialog1.FileName xlBook.Close xlApp.Quit Set xlApp = Nothing Set xlBook = Nothing Set xlSheet = Nothing End If End Sub 用这个
用ADO ODBC链接Excal
再导入这种方法是把Excal 看作一张数据库中的表处理
On Error Resume Next
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim j, k As Integer
'将对象引用赋值给这些变量。
'用 Add方法 创建新的工作簿和工作表对象。
MForm.CommonDialog1.FileName = ""
MForm.CommonDialog1.ShowSave
If MForm.CommonDialog1.FileName <> "" Then
MRs.MoveFirst
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Item(1)
For j = 0 To MRs.RecordCount
For k = 0 To MRs.Fields.Count - 1
If j = 0 Then
xlSheet.Cells(j + 1, k + 1) = MForm.DataGrid1.Columns(k).Caption
Else
xlSheet.Cells(j + 1, k + 1) = CStr(MRs.Fields(MForm.DataGrid1.Columns(k).DataField).Value)
End If
Next k
If j <> 0 Then MRs.MoveNext
Next j
xlSheet.SaveAs MForm.CommonDialog1.FileName
xlBook.Close
xlApp.Quit
Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing
End If
End Sub
用这个