这次做机房收费系统,正好赶上和小伙伴们做项目,学到了很多,在导出Excel的基础上添加了一些以前没有尝试过的功能,供大家参考。
Dim MyExcel As New Microsoft.Office.Interop.Excel.Application() '定义并实例化excel工作表 MyExcel.Application.Workbooks.Add(True) '打开excel工作簿,显示excel界面
<span style="white-space:pre"> </span>MyExcel.ActiveWorkbook.Password = "123" 给excel设置密码
<span style="white-space:pre"> </span>MyExcel.Visible = False 'excel设置为不可见的 Dim Col As Integer '定义整形变量
MyExcel.WindowState = Excel.XlWindowState.xlMaximized '窗体最大化显示 MyExcel.Cells.HorizontalAlignment = 3 MyExcel.Cells.Font.Size = 18 MyExcel.Range("A2", "G2").ColumnWidth = 20 MyExcel.Cells(1, 3).value = "学生充值记录" '表头内容,在第一行,第三列 MyExcel.Range("A1", "G1").Font.Bold = True '字体加粗 MyExcel.Range("A1", "G1").Font.ColorIndex = 32 '字体颜色蓝色 MyExcel.Range("A1", "G1").Font.Size = 25 '字号25 MyExcel.Range("A1", "G1").Merge() '合并单元格
MyExcel.ActiveWindow.Caption = "学生充值记录" '在打开的excel的名称上显示:学生充值记录 MyExcel.Caption = "加油,加油" '显示的后缀
Try For Col = 0 To DataGridView1.ColumnCount - 1 'col的变化范围 MyExcel.Cells(2, Col + 1) = Me.DataGridView1.Columns(Col).HeaderText '从数据库中对应列 Next Col Catch ex As Exception MsgBox(ex.Message) '弹出捕获的消息 Exit Sub End Try Dim i As Integer '定义整型行变量 i Dim j As Integer '定义整型列变量 j Try For i = 0 To DataGridView1.RowCount - 1 For j = 0 To DataGridView1.ColumnCount - 1 '列变量取值范围 If Me.DataGridView1(j, i).Value IsNot System.DBNull.Value Then MyExcel.Cells(i + 3, j + 1) = DataGridView1(j, i).Value.ToString() '将datagridview中的数据添加到excel表中 End If Next j Next i MsgBox("导出成功!") Catch ex As Exception MsgBox(ex.Message) '弹出捕获的消息 End Try
(为实现这个功能,查了一天多的时间)
MyExcel.ActiveWorkbook.SaveAs("D:\MyDcment\" & Filename:="学生充值记录" & ".xls")