You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改VB.Net代码实现DataGridView仅导出可见列至Excel

修改VB.Net代码实现DataGridView仅导出可见列到Excel

以下是修改后的代码,仅导出DataGridView中的可见列:

Sub ExportExcel(ByVal dgv As DataGridView)
    Dim rowsTotal As Integer
    Dim visibleCols As List(Of DataGridViewColumn)
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
    Dim xlApp As New Excel.Application
    Try
        Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
        Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
        xlApp.Visible = True

        rowsTotal = dgv.RowCount
        '筛选出所有可见列
        visibleCols = dgv.Columns.Cast(Of DataGridViewColumn)().Where(Function(col) col.Visible).ToList()

        With excelWorksheet
            .Cells.Select()
            .Cells.Delete()
            '写入可见列的表头
            For iC = 0 To visibleCols.Count - 1
                .Cells(1, iC + 1).Value = visibleCols(iC).HeaderText
            Next
            '写入可见列的单元格数据
            For I = 0 To rowsTotal - 1
                For j = 0 To visibleCols.Count - 1
                    .Cells(I + 2, j + 1).Value = dgv.Rows(I).Cells(visibleCols(j).Index).Value
                Next j
            Next I
            .Rows("1:1").Font.FontStyle = "Bold"
            .Rows("1:1").Font.Size = 12

            .Cells.Columns.AutoFit()
            .Cells.Select()
            .Cells.EntireColumn.AutoFit()
            .Cells(1, 1).Select()
        End With
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Finally
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
        '正确释放Excel资源,避免进程残留
        If xlApp IsNot Nothing Then
            xlApp.Quit()
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
        End If
        xlApp = Nothing
    End Try
End Sub

关键改动说明:

  • 参数类型从Object改为DataGridView,提升类型安全性,无需额外类型转换
  • 新增visibleCols列表,通过LINQ筛选出DataGridView中所有Visible属性为True的列
  • 表头写入逻辑改为遍历visibleCols,仅导出可见列的标题文本
  • 数据写入时,通过可见列的原索引获取对应单元格的值,确保数据对应正确
  • 优化Excel资源释放流程,添加xlApp.Quit()和Marshal.ReleaseComObject,防止Excel进程后台残留

调用方式保持不变:ExportExcel(你的DataGridView实例名)

内容的提问来源于stack exchange,提问作者Bislim Pireva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:45:27