我可能是盲人,但這與正常的export-to-excel有點不同。我已經創建了一個解決方案,並想知道這是否是最好的方法。或者即使有另一種方式來做到這一點。將dataGridView中的顯示列導出到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
謝謝您的反饋。布萊恩。
究竟什麼是你的問題?這只是「這個代碼寫得好嗎?」? – davidsbro
問題是,「是否有另一種方法可以做得更好?或者這是做到這一點的方法嗎?」我第一次遇到這種情況,所以我想確保我做對了。 – PHBeagle