在从数据库检索出来数据并显示在datagridview控件上面之后,如何导入到Excel中,机房收费系统的业务功能中也是一个小小的问题。通过实例驱动,分享给大家其中的实现方法
在UI层的用户界面设置如图:导出其中的数据到excel还要借用上一篇博客(
VB.Net机房收费系统(三层)——用datagirdview 控件显示数据库数据
)当我们用datagrideview 控件显示出来数据之后,添加引用并实现:Imports Microsoft.Office.Interop
Private Sub cmdToExcel_Click(sender As Object,e As EventArgs) Handles cmdToExcel.Click Dim xlApp,xlBook,xlSheet As Object xlApp = CreateObject("Excel.Application") xlBook = xlApp.Workbooks.Add xlSheet = xlBook.Worksheets(1) Dim rowindex,colindex As Integer rowindex = 1 '行 colindex = 0 '列 xlSheet = xlApp.Worksheets("sheet1") '打開sheet1那頁 Dim a As New DataSet Dim table As New System.Data.DataTable table = DataGridView1.DataSource Dim row As DataRow '定義row為表格的行 Dim col As DataColumn '定義col為表格的列 '把表格的每一列寫到EXCEL去 For Each col In table.Columns colindex = colindex + 1 xlApp.Cells(1,colindex) = col.ColumnName Next '把表格的每一行寫到EXCEL去 For Each row In table.Rows rowindex = rowindex + 1 colindex = 0 For Each col In table.Columns colindex = colindex + 1 xlApp.Cells(rowindex,colindex) = row(col.ColumnName) Next Next xlApp.Visible = True End Sub
原文链接:https://www.f2er.com/vb/258909.html