vb中导出datagrid内容为excel表格
时间: 2024-06-12 13:04:14 浏览: 173
以下是VB中导出DataGridView内容为Excel表格的示例代码:
```
Private Sub ExportToExcel(ByVal dgv As DataGridView)
' 创建Excel对象
Dim excel As Object = CreateObject("Excel.Application")
' 创建工作簿
Dim workbook As Object = excel.Workbooks.Add()
' 创建工作表
Dim worksheet As Object = workbook.Worksheets(1)
' 设置单元格格式
Dim range As Object = worksheet.Range("A1").EntireRow
range.Font.Bold = True
range.Interior.ColorIndex = 15
range.Font.ColorIndex = 2
' 填充表头
For i As Integer = 0 To dgv.Columns.Count - 1
worksheet.Cells(1, i + 1) = dgv.Columns(i).HeaderText
Next
' 填充数据
For i As Integer = 0 To dgv.Rows.Count - 1
For j As Integer = 0 To dgv.Columns.Count - 1
worksheet.Cells(i + 2, j + 1) = dgv.Rows(i).Cells(j).Value
Next
Next
' 自动调整列宽
range = worksheet.Range("A1").CurrentRegion
range.Columns.AutoFit()
' 保存文件
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "Excel文件|*.xlsx"
If saveFileDialog.ShowDialog() = DialogResult.OK Then
workbook.SaveAs(saveFileDialog.FileName)
MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
' 关闭Excel对象
excel.Quit()
End Sub
```
在调用该函数时,只需传入DataGridView的实例即可:
```
ExportToExcel(DataGridView1)
```
阅读全文