在DataGridView中导出可见等于True的字段

时间:2017-08-14 13:52:58

标签: vb.net linq csv datagridview export-to-csv

我发现这篇关于DataGridView to CSV File的帖子,我想知道是否有人知道如何导出只有Visible = True的字段?

Private Sub ExportCSVButton_Click(sender As Object, e As EventArgs) Handles ExportCSVButton.Click
        Dim headers = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                       Select header.HeaderText).ToArray
        Dim rows = From row As DataGridViewRow In PadGridView.Rows.Cast(Of DataGridViewRow)()
                   Where Not row.IsNewRow
                   Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
        Using sw As New IO.StreamWriter("export.csv")
            sw.WriteLine(String.Join(",", headers))
            For Each r In rows
                sw.WriteLine(String.Join(",", r))
            Next
        End Using
        Process.Start("export.csv")
End Sub

1 个答案:

答案 0 :(得分:1)

获取数组中的可见列,然后您可以使用它来过滤标题和行单元格:

   Dim visibleColumns = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                   Where header.Visible
                  Select header.Index).ToArray

    Dim headers = (From header As DataGridViewColumn In PadGridView.Columns.Cast(Of DataGridViewColumn)()
                   Where visibleColumns.Contains(header.Index)
                  Select header.HeaderText).ToArray

    Dim rows = From row As DataGridViewRow In PadGridView.Rows.Cast(Of DataGridViewRow)()
               Where Not row.IsNewRow
           Select Array.ConvertAll((From x In row.Cells.Cast(Of DataGridViewCell).ToArray Where visibleColumns.Contains(x.ColumnIndex)).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))

    Using sw As New IO.StreamWriter("export.csv")
        sw.WriteLine(String.Join(",", headers))
        For Each r In rows
            sw.WriteLine(String.Join(",", r))
        Next
    End Using

    Process.Start("export.csv")