将DatagridView中的数据完美导出到Excel

来源:互联网 发布:java基础课程 精易 编辑:程序博客网 时间:2024/05/21 17:51

对于导出Excel这一功能的基本制作相信大写都已经很熟悉了。那我就简单的介绍一下。

首先:添加引用


其次:导入命名空间

  • Imports System.DataImports 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               '设置指定列的宽度(单位:字符个数)

这是最终的效果图:

原创粉丝点击