機房收費系統中,好多查詢的窗體都包含同一個功能:將數據庫中查詢到的數據顯示在MSHFlexGrid控件中,然後再把MSHFlexGrid控件中的數據導出到Excel表格中。
雖然之前做過學生信息管理系統,不過並沒有涉及到這個功能,因此記錄於此,於己,回顧反思,於大家,分享學習。
方法一:在根目錄中事先建立空的Excel表格
1、在與VB工程同一根目錄中建立將要導入數據的Excel表格;
2、在VB事件中寫代碼:
Private Sub cmdExport_Click() Dim i As Integer Dim j As Integer myFlexGrid.Redraw = False '關閉表格重畫,加快運行速度 Set xlApp = CreateObject("Excel.Application") '創建EXCEL對象 '打開已經存在的EXCEL工件簿文件 Set xlBook = xlApp.Workbooks.Open(App.Path & "\學生上機記錄.xls") xlApp.Visible = True '設置EXCEL對象可見 Set xlSheet = xlBook.Worksheets("Sheet1") '設置活動工作表 For i = 0 To myFlexGrid.Rows - 1 '行循環 For j = 0 To myFlexGrid.Cols - 1 '列循環 myFlexGrid.Row = i myFlexGrid.Col = j '保存到EXCEL xlBook.Worksheets("Sheet1").Cells(i + 1, j + 1) = myFlexGrid.Text Next j Next i myFlexGrid.Redraw = True End Sub
URL:http://www.bianceng.cn/Programming/vb/201410/45963.htm
方法二:直接引用VB中自帶的Microsoft Excel 14.0 Object Library
1、在VB設計器中,工程→引用,引用Microsoft Excel 14.0 Object Library;
2、編寫代碼:
Private Sub cmdExport_Click() Dim i As Integer Dim j As Integer Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Set xlApp = CreateObject("Excel.Application") '實例化對象xlApp xlApp.Visible = True Set xlBook = xlApp.Workbooks.Add Set xlSheet = xlBook.Worksheets(1) For i = 0 To myFlexGrid.Rows - 1 For j = 0 To myFlexGrid.Cols - 1 myFlexGrid.Row = i myFlexGrid.Col = j xlSheet.Cells(i + 1, j + 1) = Trim(myFlexGrid.Text) Next Next End Sub
第一種方法不用引用Microsoft Excel 14.0 Object Library,但必須得在根目錄下建立相應的Excel表格,第二種方法不用建立表格,直接引用Microsoft Excel 14.0 Object Library可以直接實例化,比較方便。