简体   繁体   English

如何仅将datagridview中具有隐藏列的选定行导出到excel?

[英]How can I export only selected row with hidden column in my datagridview into excel?

I am a newbie then a self taught only, I have a datagridview that will load the data from my database and it has a hidden column I want to export a selected row of data into excel but what I want to export is the only visible column in my datagridview to excel and the selected row only 我是一个新手,然后只能自学,我有一个datagridview将从数据库中加载数据,它有一个隐藏的列,我想将选定的数据行导出到excel,但是我要导出的是唯一可见的列在我的datagridview中excel和仅选定的行

I don't know how to do this right! 我不知道该怎么做!

How can I combine this? 我该如何结合呢? the selected column and only visible column will be exported in my excel 选定的列,只有可见的列将在我的Excel中导出

For i = 0 To SelectedRowCount - 1
            currentVisibleColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
            lastColumnExported = currentVisibleColumn
            For j = 1 To visibleColumnCount + 1
                Dim value = DataGridView1.Rows(i).Cells(currentVisibleColumn.Index).Value
                If value IsNot vbNullString Then
                    xlWorkSheet.Cells(i + 2, j) = value.ToString()
                    xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, DataGridView1.SelectedRows(i).Index).Value.ToString()
                End If
                currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
                lastColumnExported = currentVisibleColumn
            Next
        Next

when I do this it gives me "'Object reference not set to an instance of an object.'" 当我这样做时,它给我“对象引用未设置为对象的实例。”

Your code should be more like this: 您的代码应更像这样:

Dim columns = (From column In DataGridView1.Columns.Cast(Of DataGridViewColumn)()
               Where column.Visible
               Order By column.DisplayIndex).ToArray()

For Each row As DataGridViewRow In DataGridView1.SelectedRows
    For Each column In columns
        Dim value = row.Cells(column.Index)

        If value IsNot Nothing Then
            '...
        End If
    Next
Next

If you still get a NullReferenceException with that code then you'll need to be more specific about it to get more help but the solution to such issues is almost always the same. 如果仍然使用该代码获得NullReferenceException ,则需要对其进行更详细的说明以获得更多帮助,但解决此类问题的方法几乎总是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM