我的datagrid是与adodc相连的,我是通过下面的方式做的 Dim r As Integer, c As Integer Dim newxls As Excel.Application Dim newbook As Excel.Workbook Dim newsheet As Excel.Worksheet Set newxls = CreateObject("Excel.Application") '创建excel应用程序,打开excel2000 Set newbook = newxls.Workbooks.Add '创建工作簿 Set newsheet = newbook.Worksheets(1) '创建工作表 If frmtest.Adodc1.Recordset.RecordCount > 0 Then newxls.Visible = True For i = 0 To frmtest.DataGrid1.Columns.Count - 1 newsheet.Cells(1, i + 1) = frmtest.DataGrid1.Columns(i).Caption Next i '指定表格内容 frmtest.Adodc1.Recordset.MoveFirst Do Until frmtest.Adodc1.Recordset.EOF r = frmtest.Adodc1.Recordset.AbsolutePosition For c = 0 To frmtest.DataGrid1.Columns.Count - 1 newsheet.Cells(r + 1, c + 1) = frmtest.DataGrid1.Columns(c) Next c frmtest.Adodc1.Recordset.MoveNext Loop ErrSave: Exit Sub MsgBox Err.Description, , "提示窗口" End If
打印函数 传入 记录集 也就是你绑定控件调用得记录集 Public Function PrintInExcelRst(ByVal rst) If rst.State = 0 Then Exit Function If rst.RecordCount > 0 Then rst.MoveFirst Dim i As Integer Dim j As Integer Dim newXls As Excel.Application Dim newBook As Excel.Workbook Dim newSheet As Excel.Worksheet Set newXls = CreateObject("Excel.Application") newXls.Visible = True Set newBook = newXls.Workbooks.Add Set newSheet = newBook.Worksheets(1) '创建工作表 For i = 0 To rst.RecordCount - 1 For j = 0 To rst.Fields.Count - 1
Dim r As Integer, c As Integer
Dim newxls As Excel.Application
Dim newbook As Excel.Workbook
Dim newsheet As Excel.Worksheet
Set newxls = CreateObject("Excel.Application") '创建excel应用程序,打开excel2000
Set newbook = newxls.Workbooks.Add '创建工作簿
Set newsheet = newbook.Worksheets(1) '创建工作表 If frmtest.Adodc1.Recordset.RecordCount > 0 Then
newxls.Visible = True
For i = 0 To frmtest.DataGrid1.Columns.Count - 1
newsheet.Cells(1, i + 1) = frmtest.DataGrid1.Columns(i).Caption
Next i
'指定表格内容
frmtest.Adodc1.Recordset.MoveFirst
Do Until frmtest.Adodc1.Recordset.EOF
r = frmtest.Adodc1.Recordset.AbsolutePosition
For c = 0 To frmtest.DataGrid1.Columns.Count - 1
newsheet.Cells(r + 1, c + 1) = frmtest.DataGrid1.Columns(c)
Next c
frmtest.Adodc1.Recordset.MoveNext
Loop
ErrSave:
Exit Sub
MsgBox Err.Description, , "提示窗口"
End If
Public Function PrintInExcelRst(ByVal rst)
If rst.State = 0 Then Exit Function
If rst.RecordCount > 0 Then
rst.MoveFirst
Dim i As Integer
Dim j As Integer
Dim newXls As Excel.Application
Dim newBook As Excel.Workbook
Dim newSheet As Excel.Worksheet
Set newXls = CreateObject("Excel.Application")
newXls.Visible = True
Set newBook = newXls.Workbooks.Add
Set newSheet = newBook.Worksheets(1) '创建工作表
For i = 0 To rst.RecordCount - 1
For j = 0 To rst.Fields.Count - 1
newSheet.Cells(i + 1, j + 1) = rst(j)
Next j
rst.MoveNext
Next i
End If
End Function