Datagrid 数据导出到excel 最新的速度最快的

来源:互联网 发布:客厅改装 知乎 编辑:程序博客网 时间:2024/06/05 14:56

         当然了,你必须首先确保装上了Excel,因为需要首先在 项目->添加引用中选择 com 标签后,添加 Microsoft   Excel  11.0 object library.

Public Function Datagrid2Excel(ByVal Dtg As DataGrid)
        If Dtg.VisibleRowCount > 0 Then
            Try

                Dim datav As New DataView
                If TypeOf Dtg.DataSource Is DataView Then
                    datav = CType(Dtg.DataSource, DataView)
                ElseIf TypeOf Dtg.DataSource Is DataSet Then
                    datav = CType(Dtg.DataSource, DataSet).Tables(0).DefaultView
                ElseIf TypeOf Dtg.DataSource Is DataTable Then
                    datav = CType(Dtg.DataSource, DataTable).DefaultView
                End If
                Dim i, j As Integer
                Dim rows As Integer = datav.Table.Rows.Count
                Dim cols As Integer = datav.Table.Columns.Count
                Dim DataArray(rows - 1, cols - 1) As String
                Dim myExcel As Excel.Application = New Excel.Application
                For i = 0 To rows - 1
                    For j = 0 To cols - 1
                        If IsDBNull(datav.Table.Rows(i).Item(j)) Then
                            DataArray(i, j) = ""
                        Else
                            DataArray(i, j) = datav.Table.Rows(i).Item(j)
                        End If
                    Next
                Next
                myExcel.Application.Workbooks.Add(True)
                myExcel.Visible = True
                For j = 0 To cols - 1
                    myExcel.Cells(1, j + 1) = datav.Table.Columns(j).ColumnName
                Next
                myExcel.Range("A2").Resize(rows, cols).Value = DataArray

            Catch exp As Exception
                MessageBox.Show(exp.Message)
            End Try
        Else
            MessageBox.Show("没有数据!")
        End If
    End Function

感受:网络是最好的老师,只要你自觉的去学习。