将数据从datagridview导出到Excel时。 [英] While Exporting Data from datagridview to Excel.

查看:68
本文介绍了将数据从datagridview导出到Excel时。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的Coders,



我设法将datagridview的数据导出到Excel文件,但我无法获取datagridview的列名。请帮我解决一下这个。代码如下。



Dear Coders,

I managed to export the data of a datagridview to an Excel File but i can''t able to fetch the column names of the datagridview. Please help me with this. The Code is below.

Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer

'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)

With ExcelSheet
    For i = 1 To Me.DataGridView1.RowCount
        .cells(i, 1) = Me.DataGridView1.Rows(i - 1).Cells("sl_no").Value
        For j = 1 To DataGridView1.Columns.Count - 1
            .cells(i, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
        Next
    Next
End With

ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing

推荐答案

看看它会工作
Check out this It''ll Work
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
 
'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
 
With ExcelSheet
    ' Starting Loop on Column Headers to Export in Excel
    For i = 1 To Me.DataGridView1.ColumnCount
        .Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
    Next
    ' Starting to Export Datas in Grid to Excel
    For i = 1 To Me.DataGridView1.RowCount
        For j = 0 To DataGridView1.Columns.Count - 1
            ' Here I use "i + 1" to Define Rows,
            ' Because Cells of Row "i" is already used to Store Column Header Data...
            .cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
        Next
    Next
End With
 
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing


看下面的文章,第一个使用两种方法通过数据gridview将数据导出到Excel,还有另外一篇文章,它有9个解决方案将不同的数据导出到Excel,包括datagridview,这两个对你有帮助:

Excel to Datatable and Datatable到Excel [ ^ ]

9将数据导出到Excel for ASP.NET [ ^ ]
Look below articles,the first uses two ways to export data to Excel through data gridview,also another article, which has 9 solutions to export different data to Excel including datagridview, both is helpful to you:
Excel to Datatable and Datatable to Excel[^]
9 Solutions to Export Data to Excel for ASP.NET[^]


这篇关于将数据从datagridview导出到Excel时。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆