机房收费系统——在VB中将MSHFlexGrid控件中的数据导出到Excel


               机房收费系统中,好多查询的窗体都包含同一个功能:将数据库中查询到的数据显示在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

 

           方法二:直接引用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可以直接实例化,比较方便。

 

你可能感兴趣的:(Excel)