Winform中打印 dataGridView里的内容

article/2025/11/1 2:27:09

最近评论问题比较多,这是几年前得代码了,今天正好有时间我重新整理了下代码把源码Demo发上来给大家看看互相学习。

有问题随时交流。没有积分得私信我发你。

Demo地址:DataGirdView打印.rar-C#文档类资源-CSDN下载

//调用GridPrinter首先添加一个printDocument控件并激活其printDocument_PrintPage事件写:实例化类GridPrinter gridPrinter;private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{bool more = gridPrinter.DrawDataGridView(e.Graphics);if (more == true)e.HasMorePages = true;
}//定义一个bool方法private bool InitializePrinting()
{PrintDialog printDialog = new PrintDialog();//printDialog.AllowCurrentPage = true;//printDialog.AllowPrintToFile = true;//printDialog.AllowSelection = true;//printDialog.AllowSomePages = true;//printDialog.PrintToFile = true;//printDialog.ShowHelp = true;//printDialog.ShowNetwork = true;if (printDialog.ShowDialog() != DialogResult.OK)return false;printDocument.DocumentName = "人员基本信息";printDocument.PrinterSettings = printDialog.PrinterSettings;printDocument.DefaultPageSettings =   printDialog.PrinterSettings.DefaultPageSettings;printDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);gridPrinter = new GridPrinter(dataGridView1, printDocument, true, true, "人员基本信息", new Font("黑体", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);return true;
}//打印按钮中添加如下代码:if (InitializePrinting())
{PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();printPreviewDialog.Document = printDocument;printPreviewDialog.ShowDialog();
}

//运行效果如图所示:

点确定按钮后如图所示:

//公用打印类using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;public class GridPrinter
{// the grid to printprivate DataGridView dataGridView;// the PrintDocumentprivate PrintDocument printDocument;// center printout?private bool centerOnPage;// has a title?private bool hasTitle;// titleprivate string title;// fontprivate Font titleFont;// title colorprivate Color titleColor;// use paging?private bool paging;// row printingstatic int currentRow;// page printingstatic int pageNumber;// page widthprivate int pageWidth;// page heightprivate int pageHeight;// left marginprivate int leftMargin;// top marginprivate int topMargin;// right marginprivate int rightMargin;// bottom marginprivate int bottomMargin;// y location placeholderprivate float currentY;// grid sizesprivate float rowHeaderHeight;private List<float> rowsHeight;private List<float> columnsWidth;private float dataGridViewWidth;// column stop pointsprivate List<int[]> mColumnPoints;private List<float> mColumnPointsWidth;private int mColumnPoint;public GridPrinter(DataGridView objDataGridView, PrintDocument objPrintDocument, bool bCenterOnPage, bool bHasTitle, string sTitle, Font objTitleFont, Color objTitleColor, bool bPaging){dataGridView = objDataGridView;printDocument = objPrintDocument;centerOnPage = bCenterOnPage;hasTitle = bHasTitle;title = sTitle;titleFont = objTitleFont;titleColor = objTitleColor;paging = bPaging;pageNumber = 0;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 metricsprivate void Calculate(Graphics g){if (pageNumber == 0){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;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;}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 printingprivate void DrawHeader(Graphics g){currentY = (float)topMargin;if (paging){pageNumber++;string PageString = "Page " + pageNumber.ToString();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 - (float)rightMargin - (float)leftMargin, 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;elseTitleFormat.Alignment = StringAlignment.Near;RectangleF TitleRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(title, titleFont).Height);g.DrawString(title, titleFont, new SolidBrush(titleColor), TitleRectangle, TitleFormat);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;elseCellFormat.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 functionprivate 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);elseg.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;elseCellFormat.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;}elsereturn true;}// the main grid printing methodpublic bool DrawDataGridView(Graphics g){try{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;}}
}


http://chatgpt.dhexx.cn/article/ehPY3D1C.shtml

相关文章

C# DataGridView 使用

1、//dataGridView標題居中 dataGridView2.ColumnHeadersDefaultCellStyle.Alignment DataGridViewContentAlignment.MiddleCenter;2、//dataGrideView文本居中 dataGridView2.RowsDefaultCellStyle.Alignment DataGridViewContentAlignment.MiddleCenter;3、//dataGridVie…

C#中DataGridView操作

DataGridView官方介绍 1.DataGridView增加数据 // 先清理&#xff0c;防止数据脏乱 skinDataGridView1.Rows.Clear(); // 获取最新行的索引 int index skinDataGridView1.Rows.Add(); // 添加数据 skinDataGridView1.Rows[index].Cells[0].Value "第index行第一列&quo…

C#Winform的DataGridView控件使用详解1—七种DataGridViewColumn类型使用方法

C#Winform的DataGridView控件使用详解1—七种DataGridViewColumn类型使用方法 DataGirdView控件Column类型DataGridViewButtonColumn列&#xff1a;按钮DataGridViewCheckBoxColumn列&#xff1a;复选框DataGridViewComboBoxColumn列&#xff1a;下拉框DataGridViewImageColumn…

DataGridView简单介绍

在很多软件中都需要查询数据&#xff0c;显示数据&#xff0c;机房收费系统也是非常多的。在这里我们就用到了DataGridView控件。 一&#xff0c;概述&#xff1a; 使用 DataGridView控件&#xff0c;可以显示和编辑来自多种不同类型的数据源的表格数据。它可以通过设置属性直接…

C#Winform的DataGridView控件使用详解2—DataGridView表格样式设置及表格操作

C#Winform的DataGridView控件使用详解2—DataGridView表格样式设置及表格操作 DataGridView表格样式设置DataGridView行序号设置 右键弹出控件表格操作DataGridView新建行DataGridView删除行DataGridView清除内容DataGridView复制DataGridView粘贴 在展示和处理二维数据时&…

C# DataGridView控件的基础应用实例

目录 引言一、界面简介二、初始化三、添加一行数据四、允许修改表格五、复制选择的数据六、复制所有数据七、读一行数据八、读所有数据九、查找名字记录十、删除一行数据十一、删除多行数据十二、清除所有行十三、删除所有列十四、其它&#xff1a;选中单元格十五、最后 引言 …

基于用户的协同过滤个性化音乐推荐系统毕业设计

基于用户的协同过滤个性化音乐推荐系统 摘 要 互联网发展到如今已经完完全全的改变了的生活方式&#xff0c;融入了日常生活&#xff0c;包括交流&#xff0c;出行&#xff0c;消费&#xff0c;娱乐等。与此同时&#xff0c;音乐数据也在与日俱增的变化着。用户在访问一个…

基于深度学习的音乐推荐系统

♚ 作者&#xff1a;沂水寒城&#xff0c;CSDN博客专家&#xff0c;个人研究方向&#xff1a;机器学习、深度学习、NLP、CV Blog: http://yishuihancheng.blog.csdn.net 推荐系统在我们日常生活中发挥着非常重要的作用&#xff0c;相信实际从事过推荐相关的工程项目的人或多或少…

(附源码)计算机毕业设计SSM基于java的音乐推荐系统

&#xff08;附源码&#xff09;计算机毕业设计SSM基于java的音乐推荐系统 项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技…

【计算机毕业设计】Java基于协同过滤算法的音乐推荐系统

毕设帮助、开题指导、源码交流&#xff0c;联系方式见文末。。 音乐检索系统的开发目的是使音乐检索模式转变成信息管理&#xff0c;为音乐检索人员提供方便条件。对音乐检索的实际情况进行调研之后&#xff0c;进行详细的需求分析&#xff0c;对现有的管理模式进行改进&#x…

java基于springboot+vue协同过滤算法的音乐推荐系统

音乐是人类永恒的话题&#xff0c;无论是在古代还是现代人们对音乐都有一种非常的热爱在里面&#xff0c;同时音乐也寄语了人们对美好事物的憧憬&#xff0c;很多时候人们在试听音乐的时候并不能够及时的找到适合自己的音乐&#xff0c;而且当下很多音乐都是收费的&#xff0c;…

[附源码]java毕业设计网易云音乐推荐系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

基于python的音乐推荐系统

基于python的音乐推荐系统 算法:基于用户的协同过滤推荐算法 语言:python 数据库:sqlite 框架:django 编号:8448648225698568爱喝可乐的大学生

SpringBoot+Vue项目个性化音乐推荐系统

文末获取源码 开发语言&#xff1a;Java 框架&#xff1a;springbootvue Node&#xff1a;node.js JDK版本&#xff1a;JDK1.8 服务器&#xff1a;tomcat7 数据库&#xff1a;mysql 5.7/8.0 数据库工具&#xff1a;Navicat11 开发软件&#xff1a;eclipse/idea,Visual Maven包…

如何使用Python实现音乐推荐系统

如何使用Python实现音乐推荐系统 在我的大学三年中&#xff0c;我最大的技术难题之一是如何使用Python实现音乐推荐系统。音乐推荐系统是基于用户听歌历史、用户喜好和音乐特征等因素&#xff0c;为用户推荐最合适的音乐。在这篇博客中&#xff0c;我将分享我是如何使用Python…

动手写简单的音乐推荐系统

简单音乐推荐系统的设计与实现 本文提供两种简单的传统音乐推荐系统&#xff08;next-songs 方向&#xff09;的思路与实现。&#xff08;数学原理和机器学习方法从略&#xff09; 下文仅给出思路以及关键代码&#xff0c;完整代码实现见: https://github.com/cdfmlr/murecom…

基于hadoop大数据的音乐推荐系统

1 简介 今天向大家介绍一个帮助往届学生完成的毕业设计项目&#xff0c;基于hadoop大数据的音乐推荐系统。 1.4 Hadoop优势&#xff08;4高&#xff09; 1.5 Hadoop 组成&#xff08;面试重点&#xff09; 1.5.1 HDFS 架构概述 Hadoop Distributed File System &#xff0c;简…

python音乐推荐系统_音乐推荐系统

音乐频道推荐业务,支持各个产品业务和策略。这里我先使用CB+CF+LR实现推荐部分,下面具体展开: 一、推荐系统流程图 CB,CF算法在召回阶段使用,推荐出来的item是粗排的,利用LR算法,可以将CB,CF召回来的item进行精排,然后选择分数最高,给用户推荐出来。后续我们可以采用…

(附源码)计算机毕业设计SSM音乐推荐系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…