将dataGridView中显示的列导出到Excel

时间:2014-01-29 17:56:57

标签: vb.net winforms visual-studio-2012 datagridview export-to-excel

我可能会失明,但这与普通的出口到卓越有点不同。我已经创建了一个解决方案,并想知道这是否是最佳方式。或者即使有另一种方法可以做到这一点。

背景:WinForms,VisualBasic,VS2012,N-Tier(后端是DB2)。我的DTO按DB2表的顺序设置。我的用户希望在DGV中按特定顺序查看字段,并能够以相同的顺序导出字段。用户还可以重新排列和隐藏列。不应导出隐藏列。

我的解决方案确实从dgv字段到excel正常复制。区别在于我必须使用DataGridViewColumnCollection,以便我可以利用DataGridViewElementStates.Visible来确保我只导出可见列。

这是代码。

Private Sub ExportToExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportToExcelToolStripMenuItem.Click
  If((dgv.Columns.Count = 0) Or (dgv.Rows.Count = 0)) Then Exit Sub
  Dim XlApp = New Excel.Application With {.Visible = True}
  xlApp.Workbooks.Add(Excel.XlSheetType.xlWorksheet)
  Dim xlWS = xlApp.ActiveSheet
  xlWS.Name = "Exported Data"

  'Copy visible data from DGV to Excel
  Dim columnCollection As DataGridViewColumnCollection = dgv.Columns
  Dim currentVisibleColumn AS DataGridViewColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
  Dim lastColumnExported As DataGridViewColumn = currentVisibleColumn
  Dim visibleColumntCount As Integer = columnCollection.GetColumnCount(DataGridViewElementStates.Visible)

  'Finally export the data
  For c = 1 to VisibleColumnCount
     xlWS.Cells(1,c) = currentVisibleColumn.HeaderText
     currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
     lastColumnExported = currentVisibleColumn
  Next

  'Only export visible cells
  For r = 0 To dgv.Rows.Count - 1
     'Reset values
     currentVisibleColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
     lastColumnExported = currentVisibleColumn
     For c = 1 to visibleColumnCount
         Dim value = dgv.Rows(r).Cells(currentVisibleColumn.Index).Value
         If value <> vbNullString Then
            xlWS.Cells(r + 2, c) = value.ToString()
         End If
         currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
         lastColumnExported = currentVisibleColumn
     Next
  Next

  'Autosize columns in excel
  Dim columns = xlWS.UsedRange.Columns
  columns.AutoFit()
End Sub

感谢您的反馈。 布赖恩。

2 个答案:

答案 0 :(得分:0)

Theres是更简单的方法,它是在细胞复制过程的每次迭代中执行if statmente。您询问该索引处的列是否可见,如果该列可见,则复制,否则您将该列倾斜并接下来。

答案 1 :(得分:0)

谢谢你的工作只需改变两行

如果值为vbNullString则

          ElseIf value IsNot vbNullString Then