You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现DataGridView打印时第一列左对齐其余列右对齐

解决方案

问题根源

你当前打印逻辑中的对齐判断分支完全错误,所有情况都强制设置为右对齐,没有匹配界面上配置的第一列左对齐规则:

  • 原Select Case判断条件重复,仅校验了右对齐枚举值,没有覆盖左对齐的场景
  • 所有分支包括Case Else都设置fmt.Alignment = StringAlignment.Far(对应右对齐),导致最终所有列打印时都统一右对齐

修改方法

替换PrintDocument1_PrintPage事件中对应的Select Case代码块即可,修改后的代码如下:

Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
    ' 匹配所有左对齐配置
    Case DataGridViewContentAlignment.TopLeft, _
         DataGridViewContentAlignment.MiddleLeft, _
         DataGridViewContentAlignment.BottomLeft
        fmt.Alignment = StringAlignment.Near
        rc.Offset(-170, -30)
    ' 匹配所有右对齐配置
    Case DataGridViewContentAlignment.TopRight, _
         DataGridViewContentAlignment.MiddleRight, _
         DataGridViewContentAlignment.BottomRight
        fmt.Alignment = StringAlignment.Far
        rc.Offset(-170, -30)
    ' 其他对齐方式默认居中,可按需调整
    Case Else
        fmt.Alignment = StringAlignment.Center
        rc.Offset(-170, -30)
End Select

额外优化建议

你当前表头是硬编码空格拼接的固定字符串,对齐无法自动适配,如果需要表头也和数据列对齐规则保持一致,可以去掉硬编码的表头字符串,改为循环列对象动态绘制,自动读取列的对齐配置进行渲染。

内容的提问来源于stack exchange,提问作者Said

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:39:03