C#DataGridView打印代码

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

        ///

        ///打印DataGridView

        ///

        /// 要打印的DataGridView

        /// 标题

        /// /// 第二标题,可以为null

        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;

                        //列宽


标题名称:C#DataGridView打印代码
链接分享:http://azwzsj.com/article/jposid.html