.net中將DataGridView內的資料匯出為Excel表格

來源:互聯網
上載者:User

       對於DataGrid相信大家並不陌生,那DataGridView與他有什麼關係呢?關係就是後者是前者的升級版,到了很多最佳化的功能。比如多種資料顯示方式。它們共同的作用的作用是顯示多條資訊。這篇文章中我們將要解釋的是如何將DataGridView中的資料匯出到excel表格中。

一.先簡單介紹一下DataGridView

DataGridView由兩種基本的對象組成:儲存格(cell)和組(band)。所有的儲存格都繼承自DataGridViewCell基類。兩種類型的組(或稱集合)DataGridViewColumn和DataGridViewRow都繼承自DataGridViewBand 基類,表示一組結合在一起的儲存格。需要注意的是DataGridView表示儲存格的位置為(j,i),  
j:表示儲存格所在列, i:表示儲存格所在行。這與我們平常認知的表示儲存格的表示方式不同,需要注意。

二.下面進入正題,匯出到excel,代碼如下

 

 ''' <summary>    ''' 匯出到excel    ''' </summary>    ''' <param name="DataGridName">資料表的名字</param>    ''' <returns>string</returns>    ''' <remarks>提示:成功</remarks>    Function ExportExcel(ByVal DataGridName As DataGridView) As String        Dim xlApp As New Excel.Application        Dim xlBook As Excel.Workbook        Dim xlSheet As Excel.Worksheet        xlBook = xlApp.Workbooks.Add()        xlSheet = xlBook.Worksheets("sheet1")        xlApp.Visible = True        '添加表頭        Dim cols As Integer '表頭的列數        For cols = 1 To DataGridName.Columns.Count '將相應列中的資料添加到相應的表格中            xlSheet.Cells(1, cols) = DataGridName.Columns(cols - 1).HeaderText        Next        '添加表中除了表頭的資料        Dim i As Integer        Dim j As Integer        For i = 0 To DataGridName.Rows.Count - 1            For j = 0 To DataGridName.Columns.Count - 1                If DataGridName(j, i).Value Is System.DBNull.Value Then                    xlSheet.Cells(i + 2, j + 1) = ""                Else                    xlSheet.Cells(i + 2, j + 1) = DataGridName(j, i).Value                End If            Next j        Next i        Return "匯出成功"    End Function

上面的代碼定義了一個匯出excel的方法,使用時,傳遞參數直接調用就可以了。代碼如有不足,歡迎指正。


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.