第一接触导出Excel表格是在第一次做机房收费系统的时候,能够顺利导出以满足:
现在已经很简单了这个逻辑,其实就是通过代码将Excel表格画出来:
<strong><span style="font-size:18px;"> '导出</span></strong>
<strong><span style="font-size:18px;">整段代码唯一不好理解的便是myExcel.Cell(i,j)这是从第i行第j列开始填充数据 Private Sub btnExport_Click(sender As Object,e As EventArgs) Handles btnExport.Click MessageBox.Show("导出的数据如不保存将会丢失","系统提示") Dim myExcel As New Microsoft.Office.Interop.Excel.Application() '建立Excel连接 myExcel.Application.Workbooks.Add(True) '添加一个工作薄 myExcel.Visible = True '可见 '将datagridview中的字段名导出 Dim m As Integer For m = 0 To dgvData.ColumnCount - 1 '获取datagridview的列的个数 myExcel.Cells(1,m + 1) = Me.dgvData.Columns(m).HeaderText '在Excel的第一行填写m列的datagridview的标题 Next m '往excel表里添加数据 Dim i As Integer For i = 0 To dgvData.RowCount - 1 '定义datagridview里有多少行数据要往里填充 Dim j As Integer For j = 0 To dgvData.ColumnCount - 1 '<span style="font-family: Arial,Helvetica,sans-serif;">定义datagridview里有多少列数据要往里填充</span> If Me.dgvData(j,i).Value Is System.DBNull.Value Then '进行非null判断 myExcel.Cells(i + 2,j + 1) = "" '如果是则用空代替 Else myExcel.Cells(i + 2,j + 1) = dgvData(j,i).Value '然后开始填充 End If Next j Next i End Sub</span></strong>
效果如图:
在实际的需求中这样的Excel显然是不合格的也不会是用户需要的,如果要弄出如下格式的我们又该怎么办呢?
通过学习和查阅资料会发现只要我们了解了足够多的Excel的属性和方法就可以做出来,举例如下:
<strong><span style="font-size:18px;"> Private Sub butExcel_Click(sender As Object,e As EventArgs) Handles btnExcel.Click MessageBox.Show("导出的数据如不保存将会丢失","系统提示") Dim myExcel As New Microsoft.Office.Interop.Excel.Application() '建立Excel连接 myExcel.Application.Workbooks.Add(True) myExcel.Visible = True Dim i,j,k As Integer '定义变量 myExcel.Cells.HorizontalAlignment = 3 '定义单元格文本对齐方式 myExcel.Cells.Font.Size = 14 '定义文本字体大小 Select Case cmbTable.Text.Trim() Case "党政人才类别统计表1" myExcel.Range("A2").ColumnWidth = 45 '设定指定单元格集的列宽,此处是指A2所对应的列 myExcel.Range("B2","P2").ColumnWidth = 16 <span style="font-family: Arial,sans-serif;">'设定指定单元格集的列宽,此处是指B2和P2所对应的列</span> myExcel.Cells(1,16) = cmbTable.Text myExcel.Range("A1","P1").Merge() '合并单元格 myExcel.Range("A1","P1").Font.Bold = True '字体加粗 'myExcel.Range("A1","P1").Font.ColorIndex = 32 '字体颜色蓝色 myExcel.Range("A1","P1").Font.Size = 25 '添加表头b myExcel.Range("B2","E2").Merge() myExcel.Range("F2","J2").Merge() myExcel.Range("F2","J2").Font.Bold = True '字体加粗 'myExcel.Range("F2","J2").Font.ColorIndex = 32 '字体颜色蓝色 myExcel.Range("F2","J2").Font.Size = 20 myExcel.Cells(2,6) = "学历" '给第二行第六列的单元格赋值 myExcel.Range("K2","P2").Merge() '合并单元格 myExcel.Range("K2","P2").Font.Bold = True '字体加粗 'myExcel.Range("K2","P2").Font.ColorIndex = 32 '字体颜色蓝色 myExcel.Range("K2","P2").Font.Size = 20 myExcel.Cells(2,11) = "年龄" End Select For k = 0 To dgvData.ColumnCount - 1 myExcel.Cells(3,k + 1) = dgvData.Columns(k).HeaderText Next k '添加数据 For i = 0 To dgvData.RowCount - 1 For j = 0 To dgvData.ColumnCount - 1 myExcel.Cells(i + 4,i).Value Next Next End Sub </span></strong>
效果图: