您的位置:首页 > 编程语言 > VB

Vb.net dataGridView导出EXCEL

2016-12-16 15:06 302 查看
Public Function daochu(ByVal x As DataGridView) As Boolean '导出到Excel函数
Try
If x.Rows.Count <= 0 Then '判断记录数,如果没有记录就退出
MessageBox.Show("没有记录可以导出", "没有可以导出的项目", MessageBoxButtons.OK, MessageBoxIcon.Information)
Return False
Else '如果有记录就导出到Excel
Dim xx As Object : Dim yy As Object
xx = CreateObject("Excel.Application") '创建Excel对象
yy = xx.workbooks.add()
Dim i As Integer, u As Integer = 0, v As Integer = 0 '定义循环变量,行列变量
For i = 1 To x.Columns.Count '把表头写入Excel
yy.worksheets(1).cells(1, i) = x.Columns(i - 1).HeaderCell.Value
Next
Dim str(x.Rows.Count - 1, x.Columns.Count - 1) '定义一个二维数组
For u = 1 To x.Rows.Count '行循环
For v = 1 To x.Columns.Count '列循环
If x.Item(v - 1, u - 1).Value.GetType.ToString <> "System.Guid" Then
str(u - 1, v - 1) = x.Item(v - 1, u - 1).Value
Else
str(u - 1, v - 1) = x.Item(v - 1, u - 1).Value.ToString
End If
Next
Next
yy.worksheets(1).range("A2").Resize(x.Rows.Count, x.Columns.Count).Value = str '把数组一起写入Excel
yy.worksheets(1).Cells.EntireColumn.AutoFit() '自动调整Excel列
' yy.worksheets(1).name = x.TopLeftHeaderCell.Value.ToString '表标题写入作为Excel工作表名称
xx.visible = True '设置Excel可见
yy = Nothing '销毁组建释放资源
xx = Nothing '销毁组建释放资源
End If
Return True
Catch ex As Exception '错误处理
MessageBox.Show(Err.Description.ToString, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) '出错提示
Return False
End Try
End Function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: