DataGridView流水打印

本文介绍了一种使用C#实现批量打印多个DataGridView的方法,该方法能够处理表格的标题、内容及页脚,并支持行合并功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

流水打印N个DataGridView中的数据

1。新建一个类,类中代码为:

 

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Data;
using System.Text;
using System.Drawing.Printing;
namespace WindowsApplication7
{
    class PrintDGV
    {
        public static StringFormat StrFormat; 
        public static int TotalWidth;        
        public static int RowPos;            
        public static int PageNo;             
        public static ArrayList ColumnLefts = new ArrayList(); 
        public static ArrayList ColumnWidths = new ArrayList();
        public static int CellHeight;        
        public  static System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument();          public static string PrintTitle = "";  // Header of pages
        public static  DataGridView dgv;       
        public static IList<DataGridView> DGVlist;
        public static List<string> AvailableColumns = new List<string>(); 
        public static List<string> TableTitle = new List<string>();
        public static List<string> OldValue=new List<string>();//要合并列前一行列值集合。
        public static List<List<string>> CoalitionColumn = new List<List<string>>();
        public static int HeaderHeight = 0;//表头高度
        public static int tmpTop = 0;//y坐标
        public static int tmpLeft = 0;//x坐标
        public static int GRDFlag = -1;//记录前一个表
        public static int GRDnumber = 0;//记录当前表
        public static bool headState = true;//表头打印标志
        public static string columnOldValue = "";

        public  delegate void delegatePring(PrintPageEventArgs e);
        public static delegatePring printTableTitle;
        public static void Print_DataGridView(IList<DataGridView> dgv1, List<string> tableTitle, delegatePring vt, List<List<string>> coalitionColumn)
        {
            PrintPreviewDialog ppvw;
            try
            {
                DGVlist = dgv1;
                TableTitle = tableTitle;
                printTableTitle = vt;
                CoalitionColumn = coalitionColumn;
                ppvw = new PrintPreviewDialog();
                ppvw.Width = Screen.PrimaryScreen.Bounds.Width;
                ppvw.Height = Screen.PrimaryScreen.Bounds.Height;
                ppvw.Document = printDoc;
                // Showing the Print Preview Page
                printDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
                printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
                if (ppvw.ShowDialog() != DialogResult.OK)
                {
                    printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
                    printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
                    return;
                }
                // Printing the Documnet
                headState = true;
                printDoc.Print();
                printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
                printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {

            }
        }

        private static void PrintDoc_BeginPrint(object sender,System.Drawing.Printing.PrintEventArgs e)
        {

                StrFormat = new StringFormat();
                StrFormat.Alignment = StringAlignment.Center;
                StrFormat.LineAlignment = StringAlignment.Center;
                StrFormat.Trimming = StringTrimming.EllipsisCharacter;
               
                GRDFlag = -1;
                GRDnumber = 0;
                dgv = DGVlist[0];
                CellHeight = dgv.ColumnHeadersHeight;
                PageNo = 1;
                RowPos = 0;
        }

        private static void PrintDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            tmpTop = e.MarginBounds.Top;//当前Y轴坐标
            tmpLeft = e.MarginBounds.Left;//当前X轴坐标
            if (headState == true)
            {
                if (printTableTitle != null)
                {
                    printTableTitle(e);
                }
                headState = false;
            }
            try
            {
                printBody(e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region  printBody
        private static void printBody(System.Drawing.Printing.PrintPageEventArgs e)
        {
            AvAndToInit();

            newTableInit(e);
            if (RowPos == 0 && tmpTop == e.MarginBounds.Top)
            {
                tmpTop += 50;
                PrintTitle = TableTitle[GRDnumber];
                printTitle(e);
                tmpTop -= 20;
            }
            printTableHead(e);
            if (GRDFlag != GRDnumber)
            {
                PrintTitle = TableTitle[GRDnumber];
                printTitle(e);
                GRDFlag = GRDnumber;
                int n = CoalitionColumn[GRDnumber].Count;
                if (n > 0)
                {
                    OldValue.Clear();
                    foreach (string str in CoalitionColumn[GRDnumber])
                    {
                        OldValue.Add("");
                    }
                }

            }
            bool br = drawRow(e);
            if (br == false)
            { return; }
            if (tmpTop + CellHeight * 5 >= e.MarginBounds.Height + e.MarginBounds.Top)
            {
                DrawFooter(e);
                PageNo++;
                e.HasMorePages = true;
                return;
            }
            GRDnumber++;
            if (GRDnumber == DGVlist.Count)
            {
                headState = true;
                e.HasMorePages = false;
                DrawFooter(e);
                return;
            }
            dgv = DGVlist[GRDnumber];
            tmpTop += CellHeight * 3;
            tmpLeft = e.MarginBounds.Left;
            printBody(e);

        }
        #endregion

        #region
        private static bool drawRow(PrintPageEventArgs e)
        {
            bool br = true;
           
            while (RowPos <= dgv.Rows.Count - 1)
            {
                DataGridViewRow GridRow = dgv.Rows[RowPos];
                CellHeight = GridRow.Height;
                if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    DrawFooter(e);
                    PageNo++;
                    e.HasMorePages = true;
                    br = false;
                    return br;
                }
                else
                {
                    int i = 0;
                    //int p = 0;
                    foreach (DataGridViewCell Cel in GridRow.Cells)
                    {
                        if (!Cel.OwningColumn.Visible) continue;

                        //if (p == 0)
                        bool coalitionState=false;
                        foreach(string  temp in CoalitionColumn[GRDnumber])
                        {
                            if(temp==Cel.OwningColumn.DataPropertyName)
                            {
                                coalitionState=true;
                                break;
                            }
                        }

                        if(coalitionState==true)
                        {
                            if (RowPos + 1 > dgv.Rows.Count - 1 )//最后一行
                            {
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i], (float)tmpTop + CellHeight, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop + CellHeight);
                            }
                            if (tmpTop + CellHeight*2 >= e.MarginBounds.Height + e.MarginBounds.Top)//一页结束
                            {
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i], (float)tmpTop + CellHeight, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop + CellHeight);
                            }
                            if (Cel.Value.ToString().Trim() == OldValue[i])//columnOldValue)
                            {
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i], (float)tmpTop, (int)ColumnLefts[i], (float)tmpTop + CellHeight);
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop + CellHeight);
                                i++;
                                continue;
                            }
                            else
                            {
                                e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
                                new SolidBrush(Cel.InheritedStyle.ForeColor),
                                new RectangleF((int)ColumnLefts[i], (float)tmpTop,
                                (int)ColumnWidths[i], (float)CellHeight), StrFormat);
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i], (float)tmpTop, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop);
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i], (float)tmpTop, (int)ColumnLefts[i], (float)tmpTop + CellHeight);
                                e.Graphics.DrawLine(Pens.Black, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop, (int)ColumnLefts[i] + (int)ColumnWidths[i], (float)tmpTop + CellHeight);
                                OldValue[i] = Cel.Value.ToString().Trim();//columnOldValue = Cel.Value.ToString().Trim();
                                i++;
                                continue;
                            }
                        }
                        e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font,
                                new SolidBrush(Cel.InheritedStyle.ForeColor),
                                new RectangleF((int)ColumnLefts[i], (float)tmpTop,
                                (int)ColumnWidths[i], (float)CellHeight), StrFormat);
                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
                                tmpTop, (int)ColumnWidths[i], CellHeight));
                        i++; 
                    }
                    tmpTop += CellHeight;
                }
                if (RowPos + 1 > dgv.Rows.Count - 1)
                {
                    RowPos = 0;
                    break;
                }
                else
                { RowPos++; }
            }
            return br;
        }
        #endregion

        #region
        private static void AvAndToInit()
        {
            AvailableColumns.Clear();
            foreach (DataGridViewColumn c in dgv.Columns)
            {
                if (!c.Visible) continue;
                AvailableColumns.Add(c.HeaderText);
            }
            TotalWidth = 0;
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                if (!GridCol.Visible) continue;
                TotalWidth += GridCol.Width;
            }
        }
        #endregion

        #region
        private static void printTitle(PrintPageEventArgs e)
        {
            e.Graphics.DrawString(PrintTitle, new Font("宋体", 16, FontStyle.Bold), Brushes.Black,
                e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(PrintTitle, new Font("宋体", 16),e.MarginBounds.Width).Width) / 2,
                tmpTop - e.Graphics.MeasureString(PrintTitle, new Font(dgv.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 50);
        }
        #endregion

        #region
        private static void newTableInit(System.Drawing.Printing.PrintPageEventArgs e)
        {
            ColumnLefts.Clear();
            ColumnWidths.Clear();
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                int tmpWidth;
                if (!GridCol.Visible) continue;
                tmpWidth = (int)(Math.Floor((double)((double)GridCol.Width *
                           ((double)e.MarginBounds.Width / (double)TotalWidth))));
                HeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                            GridCol.InheritedStyle.Font, tmpWidth).Height) + 11;
                // Save width & height of headres and ColumnType
                ColumnLefts.Add(tmpLeft);
                ColumnWidths.Add(tmpWidth);
                tmpLeft += tmpWidth;
            }
        }
        #endregion

        #region 
        private static void printTableHead(System.Drawing.Printing.PrintPageEventArgs e)
        {
            String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
            e.Graphics.DrawString(s, dgv.Font, Brushes.Black,
             e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(s, dgv.Font, e.MarginBounds.Width).Width),
             e.MarginBounds.Top + e.MarginBounds.Height + e.Graphics.MeasureString(s, dgv.Font, e.MarginBounds.Width).Height + 10);
            int i = 0;
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                if (!GridCol.Visible) continue;

                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                    new Rectangle((int)ColumnLefts[i], tmpTop,
                    (int)ColumnWidths[i], HeaderHeight));

                e.Graphics.DrawRectangle(Pens.Black,
                    new Rectangle((int)ColumnLefts[i], tmpTop,
                    (int)ColumnWidths[i], HeaderHeight));

                e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font,
                    new SolidBrush(GridCol.InheritedStyle.ForeColor),
                    new RectangleF((int)ColumnLefts[i], tmpTop,
                    (int)ColumnWidths[i], HeaderHeight), StrFormat);
                i++;
            }
            tmpTop += HeaderHeight;
        }
        #endregion

        #region 
        private static void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e)
        {
           
            string PageNum = " 第 " + PageNo.ToString()
                           + " 页";
            e.Graphics.DrawString(PageNum, dgv.Font, Brushes.Black,
                e.MarginBounds.Left + (e.MarginBounds.Width -
                e.Graphics.MeasureString(PageNum, dgv.Font,
                e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
                e.MarginBounds.Height + 31);
        }
        #endregion
    }
}

 

 

2调用前面新建哪个类的静态方法Print_DataGridView,传四参数,分别为。

 

dataGridVieew 对象集合,

各表的标题名集合,

一委托对实例,

各表要进行行合并的列集合的集合。

 

下面为调用打印方法的一段代码:

private void button1_Click(object sender, EventArgs e)
        {
          
            IList<DataGridView> dgvList = new List<DataGridView>();
            dgvList.Add(dataGridView1);//表1
            dgvList.Add(dataGridView2);//表2
            dgvList.Add(dataGridView3);//表3
            dgvList.Add(dataGridView4);//表4
            dgvList.Add(dataGridView5);//表5
           
            List<string>  TableTitle =new List<string>();
            TableTitle.Add("装置出口设置");//表1
            TableTitle.Add("装置低频轮次设置");//表2
            TableTitle.Add("装置低压轮次设置");//表3
            TableTitle.Add("装置低频减载报告");//表4
            TableTitle.Add("装置低压减载报告");//表5


            前面刚新建的类名.delegatePring vt = new 前面刚新建的类名.delegatePring(printTitle);
           
            List<List<string>> columnList = new List<List<string>>();
            columnList.Add(new List<string>());//表1
            columnList.Add(new List<string>());//表2
            columnList.Add(new List<string>());//表3
            List<string> list4 = new List<string>();
            list4.Add("equipdpname");//要合并的列名
            list4.Add("enetdpname");
            list4.Add("frequency");
            list4.Add("time");
            columnList.Add(list4);//表4
            List<string> list5 = new List<string>();
            list5.Add("equipDYname");
            list5.Add("enetDYname");
            list5.Add("Vn");
            list5.Add("Time");
            columnList.Add(list5);//表5
            PrintDGV.Print_DataGridView(dgvList, TableTitle, vt, columnList);
        }
        public static void printTitle(PrintPageEventArgs e)
        {

            string str =  "分析报告";
            Font font=new Font("宋体", 20, FontStyle.Bold);
            e.Graphics.DrawString(str,font , Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
                       e.Graphics.MeasureString(str, font,e.MarginBounds.Width).Width) / 2 - 30, PrintDGV.tmpTop -
                       e.Graphics.MeasureString(str, font, e.MarginBounds.Width).Height);        
            PrintDGV.tmpTop+=80;
        }

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值