DataGridView匯出Excel的資料表格

來源:互聯網
上載者:User

        將DataGridView中的資料匯出為Excel的資料表格,方法有很多種,下面提供一種本人認為是一個好理解,較簡單的方法。步驟如下:

1、添加引用


2、編寫代碼

Imports Microsoft.Office.Interop

’自訂過程
Public Sub ExportExcel(ByVal x As DataGridView)

'開啟Excel的應用程式

Dim xlApp As New Excel.Application

'添加一個活頁簿

Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add()

'添加一個表

Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Sheets("sheet1")


'顯示Excel

xlApp.Visible = True


'用於將DataGridView中的表賦值到Excel中的表中

Dim i As Integer

Dim j As Integer


'將DataGridView中的欄位名賦給Excel表中的第一行

Dim Cols As Integer

For Cols = 1 To x.Columns.Count

xlWorkSheet.Cells(1, Cols) = x.Columns(Cols - 1).HeaderText

Next


'將DataGridView表格的內容匯入到Excel表中

For i = 0 To x.RowCount - 2

'DataGridView中的表頭行不做為行數來計算,並且,有一空行所以減2

For j = 0 To x.ColumnCount - 1

'Excel的第一行是標題,所以應從第二行開始,即:i+2 注意DataGridView的座標是先列後行

xlWorkSheet.Cells(i + 2, j + 1) = x(j, i).Value.ToString()

Next

Next

End Sub

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.