1. 程式人生 > >將DatagridView中的資料完美匯出到Excel

將DatagridView中的資料完美匯出到Excel

對於匯出Excel這一功能的基本製作相信大寫都已經很熟悉了。那我就簡單的介紹一下。

首先:新增引用


其次:匯入名稱空間
  • Imports System.Data
    Imports Microsoft.Office.Interop

再次:是基本的程式碼,這裡拿機房收費系統中關於對充值資訊的匯出為例。由於在程式碼中做了詳細的註釋,具體的介紹就不再贅述。

  • 	 Private Sub btnExport_Click(sender As System.Object, e As System.EventArgs) Handles btnExport.Click
    	
    	        '建立Excel
    	        Dim xlApp, xlBook, xlSheet As Object
    	        xlApp = CreateObject("Excel.Application")
    	        xlBook = xlApp.Workbooks.Add
    	        xlSheet = xlBook.Worksheets(1)
    	
    	        Dim row As DataRow                               '定義row為datatable的行
    	        Dim col As DataColumn                            '定義col為datatable的列
    	        Dim rowindex, colindex As Integer
    	
    	        '開啟sheet1那頁
    	        xlSheet = xlApp.Worksheets("sheet1")
    	
    	        '賦初值
    	        rowindex = 2                                             '行(原值1)
    	        colindex = 0                                             '列
    	        '寫入欄位名
    	        For Each col In dt.Columns
    	            colindex = colindex + 1
    	            xlApp.Cells(2, colindex) = col.ColumnName            '原值是1,
    	        Next
    	
    	        '向表格中寫入具體內容
    	        For Each row In dt.Rows
    	            rowindex = rowindex + 1
    	            colindex = 0
    	            For Each col In dt.Columns
    	                colindex = colindex + 1
    	                xlApp.Cells(rowindex, colindex) = row(col.ColumnName)
    	            Next
    	        Next
    	
    	        '顯示Excel應用程式
    	        xlApp.Visible = True
    	
    	    End Sub
最後:根據自我需要,將匯出到Excel的內容做的精緻一些。可以新增表頭等。
  • 		 '*****Excel的表頭******
    	        xlSheet.cells(1, 3).value = "學生充值記錄"                '表頭內容,在第一行,第三列
    	        xlSheet.range("A1", "G1").font.bold = True                '字型加粗
    	        xlSheet.range("A1", "G1").font.colorindex = 32            '字型顏色藍色
    	        xlSheet.range("A1", "G1").font.size = 25                  '字號25
    	        xlSheet.range("A1", "G1").merge()                         '合併單元格
    	
    	        '*****Excel表內容******
    	        xlSheet.range("A2", "G2").font.bold = True               '字型加粗
    	        xlSheet.range("A2", "G2").font.size = 14                 '字號
    	        xlSheet.range("A1", "G1").HorizontalAlignment = 3        '指定單元格,水平居中(此處多餘)
    	        xlSheet.cells.horizontalalignment = 3                    '所有單元格,水平居中
    	        xlSheet.pagesetup.CenterHorizontally = True              '設定頁面水平居中
    
           xlSheet.range("A2", "G2").columnwidth = 20               '設定指定列的寬度(單位:字元個數)

這是最終的效果圖: