gridview 导出 Excel 问题
gridview里面的数据如何导出Excel,找了很久了,请指点!!!
DataGridView中的数据导入到Excel
操作步骤,主要谈谈需要注意的几点:
① DataGridView1的"AllowUserToAddRows"属性要改为False,否则会发生一个小错误,自己试试就了解喽。
② 要使用Excel表,不得不添加引用。
项目-->添加引用--> .NET-->Microsoft.Office.Interop.Excel
③实现代码,大体如下:
[vb] view plaincopyprint?
1. '为将datagridview表中数据添加到excel表中,需添加引用。
2. Imports Microsoft.Office.Interop.Excel
[vb] view plaincopyprint?
1. '导出到excel表
2. Private Sub btnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcel.Click
3. '要先添加引用才能使用下列语句Microsoft.Office.Interop.Excel.Application()
4. Dim myExcel As New Microsoft.Office.Interop.Excel.Application()
5. myExcel.Application.Workbooks.Add(True)
6. myExcel.Visible = True
7.
8. '去除datagridview1的编号列
9. Dim m As Integer
10. For m = 0 To DataGridView1.ColumnCount - 1
11. myExcel.Cells(1, m + 1) = Me.DataGridView1.Columns(m).HeaderText
12.
13. Next m
14.
15. '往excel表里添加数据
16. Dim i As Integer
17. For i = 0 To DataGridView1.RowCount - 1
18. Dim j As Integer
19. For j = 0 To DataGridView1.ColumnCount - 1
20. If Me.DataGridView1(j, i).Value Is System.DBNull.Value Then
21. myExcel.Cells(i + 2, j + 1) = ""
22. Else
23. myExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString
24. End If
25.
26. Next j
27. Next i
28.
29. End Sub