vb中,怎么将datagrid中的数据另存为Excel文件?
1个回答
展开全部
参考代码:
Public Sub import_Excel(Adc As Adodc, data_grid As DataGrid)
On Error GoTo err
Set Application = CreateObject("Excel.Application") '建立EXCEL对象
Set WorkBook = Application.Workbooks.Add() '建立一个新的Excel文档
Dim k, Column, Row, r, c As Integer
Adc.Recordset.MoveFirst
Columns = data_grid.Columns.Count '统计有多少列
Rows = Adc.Recordset.RecordCount '统计有多少行
Dim m_Array(1 To Row, 1 To Column) '声明一个二维数组
For k = 1 To Columns '这里把标头写到第一行
WorkBook.Sheets("sheet1").Cells(1, k) = data_grid.Columns(k - 1).Caption
Next k
Do While Not Adc.Recordset.EOF '循环对数组赋值
For r = 1 To Rows循环行
For c = 1 To Columns '循环列
m_Array(r, c) = Trim(Adc.Recordset.Fields(c - 1).Value)
Next c
Adc.Recordset.MoveNext
Next r
Loop
WorkBook.Sheets("sheet1").Range("A2").Resize(Row, Column).Value = m_Array '一次把数组写入到Excel---这里是快的根本
Application.Visible = True
Set Application = Nothing
Set WorkBook = Nothing
Adc.Refresh
Exit Sub
err:
MsgBox "没有记录可以导出", vbOKOnly, "出错了"
End Sub
Public Sub import_Excel(Adc As Adodc, data_grid As DataGrid)
On Error GoTo err
Set Application = CreateObject("Excel.Application") '建立EXCEL对象
Set WorkBook = Application.Workbooks.Add() '建立一个新的Excel文档
Dim k, Column, Row, r, c As Integer
Adc.Recordset.MoveFirst
Columns = data_grid.Columns.Count '统计有多少列
Rows = Adc.Recordset.RecordCount '统计有多少行
Dim m_Array(1 To Row, 1 To Column) '声明一个二维数组
For k = 1 To Columns '这里把标头写到第一行
WorkBook.Sheets("sheet1").Cells(1, k) = data_grid.Columns(k - 1).Caption
Next k
Do While Not Adc.Recordset.EOF '循环对数组赋值
For r = 1 To Rows循环行
For c = 1 To Columns '循环列
m_Array(r, c) = Trim(Adc.Recordset.Fields(c - 1).Value)
Next c
Adc.Recordset.MoveNext
Next r
Loop
WorkBook.Sheets("sheet1").Range("A2").Resize(Row, Column).Value = m_Array '一次把数组写入到Excel---这里是快的根本
Application.Visible = True
Set Application = Nothing
Set WorkBook = Nothing
Adc.Refresh
Exit Sub
err:
MsgBox "没有记录可以导出", vbOKOnly, "出错了"
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询