vb.net datagridview导出excel数据太多同一行显示两条数据代码怎么完成
时间: 2023-09-13 09:05:09 浏览: 140
vb,net datagridview的内容导入excel
4星 · 用户满意度95%
如果你的 DataGridView 中有太多的数据,导出到 Excel 中会导致同一行显示两条数据。你需要在导出时将数据分成多个工作表。
以下是示例代码,可以将 DataGridView 中的数据分成多个工作表,每个工作表最多显示2000个数据行:
```
Private Sub ExportToExcel(ByVal dgv As DataGridView)
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Dim iRowCount As Integer
Dim iColCount As Integer
Dim iSheetCount As Integer
Dim iStartRow As Integer
Dim iEndRow As Integer
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
iRowCount = dgv.RowCount
iColCount = dgv.ColumnCount
iSheetCount = Math.Ceiling(iRowCount / 2000)
For k As Integer = 1 To iSheetCount
xlWorkSheet = DirectCast(xlWorkBook.Sheets.Add(After:=xlWorkBook.Sheets(xlWorkBook.Sheets.Count), Count:=1, Type:=xlWorkSheetType), Excel.Worksheet)
xlWorkSheet.Name = "Sheet" & k.ToString()
iStartRow = (k - 1) * 2000 + 1
iEndRow = k * 2000
If iEndRow > iRowCount Then
iEndRow = iRowCount
End If
'写入表头
For j = 0 To iColCount - 1
xlWorkSheet.Cells(1, j + 1) = dgv.Columns(j).HeaderText
Next
'写入数据
For i = iStartRow To iEndRow
For j = 0 To iColCount - 1
xlWorkSheet.Cells(i - iStartRow + 2, j + 1) = dgv(j, i - 1).Value.ToString()
Next
Next
'格式化单元格
xlWorkSheet.Rows("1:1").Font.Bold = True
xlWorkSheet.Columns.AutoFit()
Next
xlApp.Visible = True
ReleaseObject(xlWorkSheet)
ReleaseObject(xlWorkBook)
ReleaseObject(xlApp)
End Sub
'释放 COM 对象
Private Sub ReleaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
```
在上面的代码中,我们将 DataGridView 分成多个工作表,并按顺序命名为 Sheet1、Sheet2、Sheet3 等等。每个工作表最多显示2000个数据行。你可以根据需要更改此限制。
阅读全文