VB.NET中如何设置DataGridView打印文本居中及调整字号
解决DataGridView打印的三个格式问题:字号、居中、行间距
看了你的DataGridView打印代码,这三个格式问题都能通过针对性调整代码解决,我给你拆解每个问题的修改方法,再附上完整的优化后代码:
1. 调大字号(支持区分表头和内容)
原代码里表头和内容共用了同一个14号粗体字体,你可以给两者分别设置不同字号,让表头更醒目、内容更清晰。比如把表头设为16号粗体,内容设为14号常规字体:
- 新增一个
contentFont对象专门用于内容打印 - 打印表头时用大字号的
headerFont,打印内容时用contentFont
2. 确保文本完全居中(适配打印页宽度)
你已经在StringFormat里设置了居中,但原代码直接用DataGridView的列宽打印,可能会因为列宽和打印页不匹配导致居中效果不明显。可以按比例缩放列宽到打印区域的宽度,既保留原列的比例,又让居中显示更自然:
- 计算打印区域总宽度和DataGridView的总列宽
- 每个单元格的打印宽度按比例计算,替代原来的
cell.Size.Width
3. 调整行间距
原代码里行与行之间只叠加了行高,没有额外间距,看起来会比较拥挤。只需要在更新行位置时,额外加上一个固定的间距值即可:
- 把
y += h改成y += h + 间距值(比如5,可根据需求调整)
完整优化后代码
With DataGridView1 ' 配置文本居中的格式参数 Using fmt As New StringFormat With { .Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center, .Trimming = StringTrimming.EllipsisCharacter, .FormatFlags = StringFormatFlags.LineLimit Or StringFormatFlags.NoWrap } Dim y As Single = e.MarginBounds.Top ' 分别定义表头和内容的字体,按需调整字号 Using headerFont As New Font("Arial", 16, FontStyle.Bold) Using contentFont As New Font("Arial", 14, FontStyle.Regular) ' 计算打印区域与DataGridView的宽度比例,用于适配列宽 Dim printTotalWidth As Single = e.MarginBounds.Width Dim dgvTotalWidth As Integer = .Columns.Cast(Of DataGridViewColumn).Sum(Function(c) c.Width) Do While mRow < .RowCount Dim row As DataGridViewRow = .Rows(mRow) Dim x As Single = e.MarginBounds.Left Dim h As Single = 0 For Each cell As DataGridViewCell In row.Cells ' 按比例计算单元格的打印宽度,适配打印页 Dim cellPrintWidth As Single = (cell.Size.Width / dgvTotalWidth) * printTotalWidth Dim rc As RectangleF = New RectangleF(x, y, cellPrintWidth, cell.Size.Height) If newpage Then ' 打印表头:大字号粗体+居中 e.Graphics.DrawString(.Columns(cell.ColumnIndex).HeaderText, headerFont, Brushes.Black, rc, fmt) Else ' 打印内容:常规字号+居中 e.Graphics.DrawString(row.Cells(cell.ColumnIndex).FormattedValue.ToString(), contentFont, Brushes.Black, rc, fmt) End If x += rc.Width h = Math.Max(h, rc.Height) Next newpage = False ' 增加行间距,这里的5可以根据自己的需求调整大小 y += h + 5 mRow += 1 If y + h > e.MarginBounds.Bottom Then e.HasMorePages = True mRow -= 1 newpage = True Exit Sub End If Loop End Using End Using End Using mRow = 0 End With
内容的提问来源于stack exchange,提问作者gkan 12




