Vb.net 如何实现报表打印
报表打印的方法有很多种,比如说先导出office 软件中然后进行排版布局,这样和方便,可是需要导入组件,而且必须安装office。下面我们看一种很实在的方法。提供全部源代码。以供朋友们学习交流。
这种方法也很简单,是使用GDI+ 把数据写到PrintDoucument中的
第一步 先引入命名空间
Imports System
Imports System.Drawing
Imports System.Drawing.Text
第二步 编写PrintDoucument 的Printpage 事件
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
下面 我们将数据表 mytab 中的数据写进PrintDoucument
先定义画笔
Dim arialfont As FontFamily = New FontFamily("arial")
Dim font As Font = New Font(arialfont, 10, FontStyle.Regular)
然后定义页边距
Dim rleft As Single = 10
Dim rtop As Single = e.MarginBounds.Top - 20
获取每一行的高度
Dim lineheight As Single = font.GetHeight(e.Graphics)
获取Mytab的行数和列数
Dim col As Integer = Mytab.Columns.Count
Dim row As Integer = Mytab.Rows.Count
获取Mytab的字段名称
Dim headline As String = ""
For i As Integer = 1 To col - 1
Dim coltext As String = Mytab.Columns(i).ColumnName.ToString
headline = headline & coltext & Space(1)
Next
获取要打印的数据
Dim listviewrows As String()
ReDim listviewrows(Me.ListView1.Items.Count + 1)
For i As Integer = 0 To row - 1
Dim lentext As String = ""
For j As Integer = 1 To col - 1
Dim maxlen As Integer = liewidth(j - 1)
Dim coltext As String
coltext = Mytab.Rows(i).item(j).ToString
lentext = lentext & coltext & Space(3)
Next
listviewrows(i) = lentext
Next
接下来就是真正的写入数据
Do
e.Graphics.DrawString(listviewrows(counts), font, Brushes.Black, rleft, rtop)
counts = counts + 1
rtop = rtop + lineheight
Loop Until rtop > e.MarginBounds.Bottom Or counts >= Mytab.Rows.Count - 1
If counts < Mytab.Rows.Count - 1 Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
END Sub
写好以后,就可以打印了
PrintDoucument.print()
到此就可以把数据表Mytab中的所有数据打印出来了