温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# DataGridView 打印代码

发布时间:2020-08-02 18:31:02 来源:网络 阅读:1344 作者:行航杭航 栏目:编程语言

 

初衷:由于之前遇到了这个问题 在网上搜索了许久 才把代码给调试好了 感觉 有必要 自己整理一下 方便“在路上”的IT……

//打印按钮为:button6

//命名空间:(只能比我的多,不能比我的少,有时候 会忘记这个最重要的地方,这是最

//三个控件:

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Drawing.Printing;

 

//第一种:

#region***打印代码 简洁版***

        private void button6_Click(object sender, EventArgs e)

        {

            if (dataGridView1.Rows.Count != 0)

            {

printDialog1.Document = this.printDocument1;

                printDialog1.ShowDialog();                                                          //设置打印文档

                printPreviewDialog1.Document = this.printDocument1;                         

                printPreviewDialog1.ClientSize = new System.Drawing.Size(800, 500);//设置打印预览时的页面大小

                printPreviewDialog1.PrintPreviewControl.Zoom = 1;                                 //显示百分比为 100%

                printPreviewDialog1.ShowDialog();

            }

            else

            {

                MessageBox.Show("打印内容为空");

            }

        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)

        {

            int r = 50; // 设置横坐标的位置

            int c = 20; // 设置纵坐标的间隔

            for (int i = 0; i < dataGridView1.Rows.Count; i++)

            {

 

                for (int j = 0; j < dataGridView1.Columns.Count; j++)

                {

 

                    e.Graphics.DrawString(dataGridView1.Rows[i].Cells[j].Value.ToString(), new Font("宋体", 8, FontStyle.Regular), Brushes.Black, r, c);

                    r = r + 100;

 

                }

                r = 50;

                c += 20;

 

            }

        }

#endregion

 

 

//第二种, 在以上命名空间 的基础上:

#region***打印代码 强大版***

private void button6_Click(object sender, EventArgs e)

{

printDialog1.Document = this.printDocument1;

    printDialog1.ShowDialog();

    PrintDataGridView pdgv = new PrintDataGridView();

    pdgv.myPrint(dataGridView1, "King公司考勤时间表", "详情");

}

#endregion

//还要建一个名为PrintDataGridView

using System;

using System.Collections.Generic;

using System.Text;

using System.Drawing.Printing;

using System.Windows.Forms;

using System.Drawing;

 

namespace King公司考勤时间表// 命名空间 别忘了改成自己的

{

    public class PrintDataGridView

    {

        public PrintDataGridView()

        {

       

        }

        static DataGridView dgv;

        //标题名称

        static string titleName = "";

        //第二标题名称

        static string titleName2 = "";

        //当前行

        static int rowIndex = 0;

        //当前页

        static int page = 1;

        //每页显示多少行

        static int rowsPerPage = 0;

        /// <summary>

        /// 打印DataGridView

        /// </summary>

        /// <param name="dataGridView">要打印的DataGridView</param>

        /// <param name="title">标题</param>

        /// /// <param name="title2">第二标题,可以为null</param>

        public void myPrint(DataGridView dataGridView, string title, string title2)

        {

            try

            {

                if (dataGridView == null)

                {

                    return;

                }

                titleName = title;

                titleName2 = title2;

                dgv = dataGridView;

                PrintPreviewDialog ppvw = new PrintPreviewDialog();

                //显示比例为100%

                ppvw.PrintPreviewControl.Zoom = 1.0;

                PrintDocument printDoc = new PrintDocument();

                //A4

                printDoc.DefaultPageSettings.PaperSize = new PaperSize("A4", 850, 1000);

                //设置边距

                printDoc.DefaultPageSettings.Margins = new Margins(60, 60, 60, 60);

                //设置要打印的文档

                ppvw.Document = printDoc;

                //最大化

                ((Form)ppvw).WindowState = FormWindowState.Maximized;

                //当前行

                rowIndex = 0;

                //当前页

                page = 1;

                //打印事件

                printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);

                printDoc.EndPrint += new PrintEventHandler(printDoc_EndPrint);

                //打开预览

                ppvw.ShowDialog();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        static void printDoc_EndPrint(object sender, PrintEventArgs e)

        {

            //当前行

            rowIndex = 0;

            //当前页

            page = 1;

            //每页显示多少行

            rowsPerPage = 0;

        }

        private static void printDoc_PrintPage(object sender, PrintPageEventArgs e)

        {

            //标题字体

            Font titleFont = new Font("宋体", 16, FontStyle.Bold);

            //标题尺寸

            SizeF titleSize = e.Graphics.MeasureString(titleName, titleFont, e.MarginBounds.Width);

            //x坐标

            int x = e.MarginBounds.Left;

            //y坐标

            int y = Convert.ToInt32(e.MarginBounds.Top - titleSize.Height);

            //边距以内纸张宽度

            int pagerWidth = e.MarginBounds.Width;

            //画标题

            e.Graphics.DrawString(titleName, titleFont, Brushes.Black, x + (pagerWidth - titleSize.Width) / 2, y);

            y += (int)titleSize.Height;

            if (titleName2 != null && titleName2 != "")

            {

                //画第二标题

                e.Graphics.DrawString(titleName2, dgv.Font, Brushes.Black, x, y);

                //第二标题尺寸

                SizeF titleSize2 = e.Graphics.MeasureString(titleName2, dgv.Font, e.MarginBounds.Width);

                y += (int)titleSize2.Height; ;

            }

            //表头高度

            int headerHeight = 0;

            //纵轴上 内容与线的距离

            int padding = 6;

            //所有显示列的宽度

            int columnsWidth = 0;

            //计算所有显示列的宽度

            foreach (DataGridViewColumn column in dgv.Columns)

            {

                //隐藏列返回

                if (!column.Visible) continue;

                //所有显示列的宽度

                columnsWidth += column.Width;

            }

            //计算表头高度

            foreach (DataGridViewColumn column in dgv.Columns)

            {

                //列宽

                int columnWidth = (int)(Math.Floor((double)column.Width / (double)columnsWidth * (double)pagerWidth));

                //表头高度

                int temp = (int)e.Graphics.MeasureString(column.HeaderText, column.InheritedStyle.Font, columnWidth).Height + 2 * padding;

                if (temp > headerHeight) headerHeight = temp;

            }

            //画表头

            foreach (DataGridViewColumn column in dgv.Columns)

            {

                //隐藏列返回

                if (!column.Visible) continue;

                //列宽

                int columnWidth = (int)(Math.Floor((double)column.Width / (double)columnsWidth * (double)pagerWidth));

                //内容居中要加的宽度

                float cenderWidth = (columnWidth - e.Graphics.MeasureString(column.HeaderText, column.InheritedStyle.Font, columnWidth).Width) / 2;

                if (cenderWidth < 0) cenderWidth = 0;

                //内容居中要加的高度

                float cenderHeight = (headerHeight + padding - e.Graphics.MeasureString(column.HeaderText, column.InheritedStyle.Font, columnWidth).Height) / 2;

                if (cenderHeight < 0) cenderHeight = 0;

                //画背景

                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray), new Rectangle(x, y, columnWidth, headerHeight));

                //画边框

                e.Graphics.DrawRectangle(Pens.Black, new Rectangle(x, y, columnWidth, headerHeight));

                ////画上边线

                //e.Graphics.DrawLine(Pens.Black, x, y, x + columnWidth, y);

                ////画下边线

                //e.Graphics.DrawLine(Pens.Black, x, y + headerHeight, x + columnWidth, y + headerHeight);

                ////画右边线

                //e.Graphics.DrawLine(Pens.Black, x + columnWidth, y, x + columnWidth, y + headerHeight);

                //if (x == e.MarginBounds.Left)

                //{

                //    //画左边线

                //    e.Graphics.DrawLine(Pens.Black, x, y, x, y + headerHeight);

                //}

                //画内容

                e.Graphics.DrawString(column.HeaderText, column.InheritedStyle.Font, new SolidBrush(column.InheritedStyle.ForeColor), new RectangleF(x + cenderWidth, y + cenderHeight, columnWidth, headerHeight));

                x += columnWidth;

            }

            x = e.MarginBounds.Left;

            y += headerHeight;

            //遍历行

            while (rowIndex < dgv.Rows.Count)

            {

                //当前行

                DataGridViewRow row = dgv.Rows[rowIndex];

                if (row.Visible)

                {

                    //行高

                    int rowHeight = 0;

                    //计算行高

                    foreach (DataGridViewCell cell in row.Cells)

                    {

                        //当前列

                        DataGridViewColumn column = dgv.Columns[cell.ColumnIndex];

                        //隐藏列返回

                        if (!column.Visible || cell.Value == null) continue;

                        //列宽

                        int tmpWidth = (int)(Math.Floor((double)column.Width / (double)columnsWidth * (double)pagerWidth));

                        //行高

                        int temp = (int)e.Graphics.MeasureString(cell.Value.ToString(), column.InheritedStyle.Font, tmpWidth).Height + 2 * padding;

                        if (temp > rowHeight) rowHeight = temp;

                    }

                    //遍历列

                    foreach (DataGridViewCell cell in row.Cells)

                    {

                        //当前列

                        DataGridViewColumn column = dgv.Columns[cell.ColumnIndex];

                        //隐藏列返回

                        if (!column.Visible) continue;

                        //列宽

                        int columnWidth = (int)(Math.Floor((double)column.Width / (double)columnsWidth * (double)pagerWidth));

                        //画边框

                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle(x, y, columnWidth, rowHeight));

                        if (cell.Value != null)

                        {

                            //内容居中要加的宽度

                            float cenderWidth = (columnWidth - e.Graphics.MeasureString(cell.Value.ToString(), cell.InheritedStyle.Font, columnWidth).Width) / 2;

                            if (cenderWidth < 0) cenderWidth = 0;

                            //内容居中要加的高度

                            float cenderHeight = (rowHeight + padding - e.Graphics.MeasureString(cell.Value.ToString(), cell.InheritedStyle.Font, columnWidth).Height) / 2;

                            if (cenderHeight < 0) cenderHeight = 0;

                            ////画下边线

                            //e.Graphics.DrawLine(Pens.Black, x, y + rowHeight, x + columnWidth, y + rowHeight);

                            ////画右边线

                            //e.Graphics.DrawLine(Pens.Black, x + columnWidth, y, x + columnWidth, y + rowHeight);

                            //if (x == e.MarginBounds.Left)

                            //{

                            //    //画左边线

                            //    e.Graphics.DrawLine(Pens.Black, x, y, x, y + rowHeight);

                            //}

                            //画内容

                            e.Graphics.DrawString(cell.Value.ToString(), column.InheritedStyle.Font, new SolidBrush(cell.InheritedStyle.ForeColor), new RectangleF(x + cenderWidth, y + cenderHeight, columnWidth, rowHeight));

                        }

                        x += columnWidth;

                    }

                    x = e.MarginBounds.Left;

                    y += rowHeight;

                    if (page == 1) rowsPerPage++;

                    //打印下一页

                    if (y + rowHeight > e.MarginBounds.Bottom)

                    {

                        e.HasMorePages = true;

                        break;

                    }

                }

                rowIndex++;

            }

            //页脚

            string footer = " " + page + " 页,共 " + Math.Ceiling(((double)dgv.Rows.Count / rowsPerPage)).ToString() + " ";

            //画页脚

            e.Graphics.DrawString(footer, dgv.Font, Brushes.Black, x + (pagerWidth - e.Graphics.MeasureString(footer, dgv.Font).Width) / 2, e.MarginBounds.Bottom);

            page++;

        }

    }

}

 

 

备注:由于书写匆忙 如果瑕疵 敬请指出(http://sdbzwh.blog.51cto.com/)此文仅供参考

 

 

 

 

 

 

 

 

 

 

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI