winform打印DataGridView I

 
private void btnPrint_Click(object sender, EventArgs e)
        {
            if (InitializePrinting("送洗衣物信息打印", this.dataGridView1))
            {
                PrintStar();
            }
        }
        static int pageNumber;
        private void PrintStar()
        {
            try
            {
                pageNumber = 0;
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.Document = printDocument1;
                printPreviewDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印机连接失败!");
            }
        }
        PrintDGV gridPrinter;
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            bool more = gridPrinter.DrawDataGridView(e.Graphics,pageNumber);
            if (more == true)
            {
                pageNumber++;
                e.HasMorePages = true;
            }
            else
            {
                pageNumber = 1;
            }
        }
        //定义一个bool方法        
        private bool InitializePrinting(string title, DataGridView dgv)
        {
            //获得默认打印机打印机名称
            string printerD = ConfigurationManager.AppSettings["PrinterD"];
            if (string.IsNullOrEmpty(printerD))
            {
                MessageBox.Show("未设置打印机,请设置.");
                frmSelPrinter frmselPrinter = new frmSelPrinter();
                frmselPrinter.ShowDialog();
            }
            string printerDD = ConfigurationManager.AppSettings["PrinterD"];
            if (string.IsNullOrEmpty(printerDD))
            {
                return false;
            }
            printDocument1.PrinterSettings.PrinterName = printerDD;
            printDocument1.DocumentName = title;
            printDocument1.DefaultPageSettings.Margins = new Margins(30, 30, 30, 30);
            gridPrinter = new PrintDGV(dgv, printDocument1, true, true, title, new Font("黑体", 14, FontStyle.Bold, GraphicsUnit.Point), true);
            return true;
        }
 
 
 using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Drawing;
namespace Code.ComTool
{
    public class PrintDGV
    {
        // the grid to print 
        private DataGridView dataGridView;
 
        // the PrintDocument 
        private PrintDocument printDocument;
 
        // center printout? 
        private bool centerOnPage;
 
        // has a title? 
        private bool hasTitle;
 
        // title 
        private string title;
 
        // font 
        private Font titleFont;
 
        // title color 
        private Color titleColor;
 
        // use paging? 
        private bool paging;

        // row printing 
        static int currentRow;
 
        // page printing 
        static int pageNumber;
 

        // page width 
        private int pageWidth;
 
        // page height 
        private int pageHeight;
 
        // left margin 
        private int leftMargin;
 
        // top margin 
        private int topMargin;
 
        // right margin 
        private int rightMargin;
 
        // bottom margin 
        private int bottomMargin;
 
        // y location placeholder 
        private float currentY;
 
        // grid sizes 
        private float rowHeaderHeight;
        private List<float> rowsHeight;
        private List<float> columnsWidth;
        private float dataGridViewWidth;
 
        // column stop points 
        private List<int[]> mColumnPoints;
        private List<float> mColumnPointsWidth;
        private int mColumnPoint;
 
        public PrintDGV(DataGridView objDataGridView, PrintDocument objPrintDocument, bool bCenterOnPage, bool bHasTitle, string sTitle, Font objTitleFont, bool bPaging)
        {
            dataGridView = objDataGridView;
            printDocument = objPrintDocument;
            centerOnPage = bCenterOnPage;
            hasTitle = bHasTitle;
            title = sTitle;
            titleFont = objTitleFont;

            paging = bPaging;
            rowsHeight = new List<float>();
            columnsWidth = new List<float>();
 
            mColumnPoints = new List<int[]>();
            mColumnPointsWidth = new List<float>();

            if (!printDocument.DefaultPageSettings.Landscape)
            {
                pageWidth = printDocument.DefaultPageSettings.PaperSize.Width;
                pageHeight = printDocument.DefaultPageSettings.PaperSize.Height;
            }
            else
            {
                pageHeight = printDocument.DefaultPageSettings.PaperSize.Width;
                pageWidth = printDocument.DefaultPageSettings.PaperSize.Height;
            }

            leftMargin = printDocument.DefaultPageSettings.Margins.Left;
            topMargin = printDocument.DefaultPageSettings.Margins.Top;
            rightMargin = printDocument.DefaultPageSettings.Margins.Right;
            bottomMargin = printDocument.DefaultPageSettings.Margins.Bottom;
 
            currentRow = 0;
        }

        // calculate printing metrics 
        private void Calculate(Graphics g)
        {
            if (pageNumber == 0)
            {
                int sumCount = 0;
                for (int a = 0; a < dataGridView.Columns.Count; a++)
                {
                    if (dataGridView.Columns[a].Visible)
                    {
                        sumCount++;
                    }
                }
                SizeF tmpSize = new SizeF();
                Font tmpFont;
                float tmpWidth;
 
                dataGridViewWidth = 0;
                for (int i = 0; i < dataGridView.Columns.Count; i++)
                {
                    tmpFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
                    if (tmpFont == null)
                        tmpFont = dataGridView.DefaultCellStyle.Font;
 
                    tmpSize = g.MeasureString(dataGridView.Columns[i].HeaderText, tmpFont);
                    //tmpWidth = tmpSize.Width;
                    tmpWidth = pageWidth / sumCount - 10;
                    rowHeaderHeight = tmpSize.Height;
 
                    for (int j = 0; j < dataGridView.Rows.Count; j++)
                    {
                        tmpFont = dataGridView.Rows[j].DefaultCellStyle.Font;
                        if (tmpFont == null)
                            tmpFont = dataGridView.DefaultCellStyle.Font;
 
                        tmpSize = g.MeasureString("Anything", tmpFont);
                        rowsHeight.Add(tmpSize.Height);
 
                        tmpSize = g.MeasureString(dataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                        if (tmpSize.Width > tmpWidth)
                            //tmpWidth = tmpSize.Width;
                            tmpWidth = pageWidth / sumCount - 10;
                    }
                    if (dataGridView.Columns[i].Visible)
                        dataGridViewWidth += tmpWidth;
                    columnsWidth.Add(tmpWidth);
                }
 
                int k;
 
                int mStartPoint = 0;
                for (k = 0; k < dataGridView.Columns.Count; k++)
                    if (dataGridView.Columns[k].Visible)
                    {
                        mStartPoint = k;
                        break;
                    }
 
                int mEndPoint = dataGridView.Columns.Count;
                for (k = dataGridView.Columns.Count - 1; k >= 0; k--)
                    if (dataGridView.Columns[k].Visible)
                    {
                        mEndPoint = k + 1;
                        break;
                    }
 
                float mTempWidth = dataGridViewWidth;
                float mTempPrintArea = (float)pageWidth - (float)leftMargin - (float)rightMargin;
 
                if (dataGridViewWidth > mTempPrintArea)
                {
                    mTempWidth = 0.0F;
                    for (k = 0; k < dataGridView.Columns.Count; k++)
                    {
                        if (dataGridView.Columns[k].Visible)
                        {
                            mTempWidth += columnsWidth[k];
                            if (mTempWidth > mTempPrintArea)
                            {
                                mTempWidth -= columnsWidth[k];
                                mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                                mColumnPointsWidth.Add(mTempWidth);
                                mStartPoint = k;
                                mTempWidth = columnsWidth[k];
                            }
                        }
                        mEndPoint = k + 1;
                    }
                }
 
                mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                mColumnPointsWidth.Add(mTempWidth);
                mColumnPoint = 0;
            }
        }
        // header printing 
        private void DrawHeader(Graphics g)
        {
            currentY = (float)topMargin;
 
            if (paging)
            {
                string PageString = "第 " + pageNumber.ToString() + "页  " + DateTime.Now.ToString("yyyy-MM-dd");
              
                StringFormat PageStringFormat = new StringFormat();
                PageStringFormat.Trimming = StringTrimming.Word;
                PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                PageStringFormat.Alignment = StringAlignment.Far;
 
                Font PageStringFont = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point);
 
                RectangleF PageStringRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - 5*(float)rightMargin , g.MeasureString(PageString, PageStringFont).Height);
 
                g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
               
                currentY += g.MeasureString(PageString, PageStringFont).Height;
            }
 
            if (hasTitle)
            {

                StringFormat TitleFormat = new StringFormat();
                TitleFormat.Trimming = StringTrimming.Word;
                TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
                if (centerOnPage)
                    TitleFormat.Alignment = StringAlignment.Center;
                else
                    TitleFormat.Alignment = StringAlignment.Near;

                Font PageStringFont = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point);
                RectangleF TitleRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(title, titleFont).Height);
 
                g.DrawString(title, titleFont, new SolidBrush(Color.Black), TitleRectangle, TitleFormat);
                //Pen p = new Pen(Color.Black, 1);
                //g.DrawLine(p, new Point(200, 65), new Point(630, 65));

                currentY += g.MeasureString(title, titleFont).Height;
            }

            float CurrentX = (float)leftMargin;
            if (centerOnPage)
                CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
 
            Color HeaderForeColor = dataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
            if (HeaderForeColor.IsEmpty)
                HeaderForeColor = dataGridView.DefaultCellStyle.ForeColor;
            SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
 
            Color HeaderBackColor = dataGridView.ColumnHeadersDefaultCellStyle.BackColor;
            if (HeaderBackColor.IsEmpty)
                HeaderBackColor = dataGridView.DefaultCellStyle.BackColor;
            SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
 
            Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
 
            Font HeaderFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
            if (HeaderFont == null)
                HeaderFont = dataGridView.DefaultCellStyle.Font;
 
            RectangleF HeaderBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowHeaderHeight);
            g.FillRectangle(HeaderBackBrush, HeaderBounds);
 
            StringFormat CellFormat = new StringFormat();
            CellFormat.Trimming = StringTrimming.Word;
            CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
 
            RectangleF CellBounds;
            float ColumnWidth;
            for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
            {
                if (!dataGridView.Columns[i].Visible) continue;
 
                ColumnWidth = columnsWidth[i];
 
                if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                    CellFormat.Alignment = StringAlignment.Far;
                else if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                    CellFormat.Alignment = StringAlignment.Center;
                else
                    CellFormat.Alignment = StringAlignment.Near;
 
                CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowHeaderHeight);
 
                g.DrawString(dataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);

                if (dataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None)
                    g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowHeaderHeight);
 
                CurrentX += ColumnWidth;
            }
 
            currentY += rowHeaderHeight;
        }

        // common row printing function 
        private bool DrawRows(Graphics g)
        {
            Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
 
            Font RowFont;
            Color RowForeColor;
            Color RowBackColor;
            SolidBrush RowForeBrush;
            SolidBrush RowBackBrush;
            SolidBrush RowAlternatingBackBrush;
 
            StringFormat CellFormat = new StringFormat();
            CellFormat.Trimming = StringTrimming.Word;
            CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
 
            RectangleF RowBounds;
            float CurrentX;
            float ColumnWidth;
            while (currentRow < dataGridView.Rows.Count)
            {
                if (dataGridView.Rows[currentRow].Visible)
                {
                    RowFont = dataGridView.Rows[currentRow].DefaultCellStyle.Font;
                    if (RowFont == null)
                        RowFont = dataGridView.DefaultCellStyle.Font;

                    RowForeColor = dataGridView.Rows[currentRow].DefaultCellStyle.ForeColor;
                    if (RowForeColor.IsEmpty)
                        RowForeColor = dataGridView.DefaultCellStyle.ForeColor;
                    RowForeBrush = new SolidBrush(RowForeColor);
 
                    RowBackColor = dataGridView.Rows[currentRow].DefaultCellStyle.BackColor;
                    if (RowBackColor.IsEmpty)
                    {
                        RowBackBrush = new SolidBrush(dataGridView.DefaultCellStyle.BackColor);
                        RowAlternatingBackBrush = new SolidBrush(dataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                    }
                    else
                    {
                        RowBackBrush = new SolidBrush(RowBackColor);
                        RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                    }
 
                    CurrentX = (float)leftMargin;
                    if (centerOnPage)
                        CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
 
                    RowBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowsHeight[currentRow]);
 
                    if (currentRow % 2 == 0)
                        g.FillRectangle(RowBackBrush, RowBounds);
                    else
                        g.FillRectangle(RowAlternatingBackBrush, RowBounds);
 
                    for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
                    {
                        if (!dataGridView.Columns[CurrentCell].Visible) continue;
                        if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
                            CellFormat.Alignment = StringAlignment.Far;
                        else if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
                            CellFormat.Alignment = StringAlignment.Center;
                        else
                            CellFormat.Alignment = StringAlignment.Near;

                        ColumnWidth = columnsWidth[CurrentCell];
                        RectangleF CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
 
                        g.DrawString(dataGridView.Rows[currentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
 
                        if (dataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None)
                            g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
 
                        CurrentX += ColumnWidth;
                    }
                    currentY += rowsHeight[currentRow];
 
                    if ((int)currentY > (pageHeight - topMargin - bottomMargin))
                    {
                        currentRow++;
                        return true;
                    }
                }
                currentRow++;
            }
 
            currentRow = 0;
            mColumnPoint++;
 
            if (mColumnPoint == mColumnPoints.Count)
            {
                mColumnPoint = 0;
                return false;
            }
            else
                return true;
        }
        // the main grid printing method 
        public bool DrawDataGridView(Graphics g,int pnumber)
        {
            try
            {
                pageNumber = pnumber;
                Calculate(g);
                DrawHeader(g);
                bool bContinue = DrawRows(g);
                return bContinue;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Winform窗体DataGridView是一个用于显示和编辑数据的控件。它可以在窗体上显示数据表格,并提供了丰富的功能,如排序、筛选、分页、编辑、删除、添加等。它可以绑定数据源,支持多种数据类型,如文本、数字、日期、图片等。同时,它还可以自定义样式和布局,以满足不同的需求。在Winform应用程序中,DataGridView是一个非常常用的控件,可以帮助我们快速地开发出功能强大的数据管理系统。 ### 回答2: Winform窗体中的DataGridView是一种用于显示和编辑二维数据的控件。它提供了一种方便且易于使用的界面来浏览和管理数据。DataGridView可以用于加载和编辑大量数据,也可以进行排序、筛选、分页和格式化等功能。 在Winform中使用DataGridView非常简单,可以在代码中手动添加列和行,也可以通过数据源绑定自动添加。使用DataGridView可以方便地处理用户输入数据的合法性检查和更新,而且能够自动实现一些其他控件无法提供的功能。例如,DataGridView自动支持单元格合并和奇偶行的颜色设置。 DataGridView的多种事件和属性也使得它非常灵活。例如,可以通过事件处理程序来动态改变单元格样式、添加自定义的排序规则和筛选器、实现拖放操作、设置行头和列头样式等。 总的来说,Winform窗体中的DataGridView是一个非常实用且强大的控件,它可以为我们提供各种数据展示和处理方案,也可以充分展示Winfrom的功能及应用优势。需要注意的是,在使用过程中我们应该使其高效运行、避免内存泄漏和意外崩溃等问题。 ### 回答3: WinForm是一种基于Windows应用程序的开发模型,可以使用Visual Studio和.NET框架进行开发。其中,DataGridViewWinForm中常见的控件之一,它提供了一个方便的方式来在应用程序窗体中呈现和编辑表格数据。 DataGridView可以显示任何数据源,包括数组、集合、DataTable、ListBox、XmlDocument,甚至自定义对象等。可以通过控制DataGridView的DataSource属性来指定数据源。 除此之外,DataGridView还提供了一系列的列和行操作方法,允许用户在运行时添加或删除行、列,调整列的宽度或居中方式等。此外还可以使用列的样式属性(如DefaultCellStyle和HeaderCellStyle)来设置单元格的外观、字体、颜色、对齐方式等。 DataGridView也支持各种事件,例如CellValueChanged、RowValidated、CellClick等来响应用户和数据的操作。 总而言之,使用WinForm中的DataGridView控件可以为应用程序提供一个功能强大的数据表格展示和编辑功能,使得用户和开发人员都能够更加方便地处理和管理大量数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值