转自:http://www.cnblogs.com/heekui/archive/2007/05/29/764531.html
在CS的WinForm中如何打印DataGridView中的内容。
网上搜索一番之后,还是在藏宝库CodeProject中找到一篇好文章《DataGridView Printing by Selecting Columns and Rows》(http://www.codeproject.com/KB/grid/PrintDataGrid_CS.aspx)
效果图
【打印设置画面】
【打印预览画面】
解决方案构成
这个打印解决方案由一个打印设置的窗体,及一个打印类组成。
可用于以下场景:
1、显示的数据量较大,但又没有必要打印全部数据的时候
2、希望打印出的列宽能自动适应页面宽度
打印类主要方法
Print_DataGridView(共有)
: 被外部类调用的主方法.
PrintDoc_BeginPrint(私有)
:初始化一些打印变量
PrintDoc_PrintPage(私有)
:执行打印工作
DrawFooter(私有)
:页脚的处理部分
打印类代码
/****************************************************
*DataGridView打印类
*原作者:AfrasiabCheraghi.
*修改者:何奎
*
***************************************************/
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Windows.Forms;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.Data;
usingSystem.Text;
namespacetestPrint
{
classPrintDGV
{
privatestaticStringFormatStrFormat;//HoldscontentofaTextBoxCelltowritebyDrawString
privatestaticStringFormatStrFormatComboBox;//HoldscontentofaBooleanCelltowritebyDrawImage
privatestaticButtonCellButton;//HoldstheContentsofButtonCell
privatestaticCheckBoxCellCheckBox;//HoldstheContentsofCheckBoxCell
privatestaticComboBoxCellComboBox;//HoldstheContentsofComboBoxCell
privatestaticintTotalWidth;//SummationofColumnswidths
privatestaticintRowPos;//Positionofcurrentlyprintingrow
privatestaticboolNewPage;//Indicatesifanewpagereached
privatestaticintPageNo;//Numberofpagestoprint
privatestaticArrayListColumnLefts=newArrayList();//LeftCoordinateofColumns
privatestaticArrayListColumnWidths=newArrayList();//WidthofColumns
privatestaticArrayListColumnTypes=newArrayList();//DataTypeofColumns
privatestaticintCellHeight;//HeightofDataGridCell
privatestaticintRowsPerPage;//NumberofRowsperPage
privatestaticSystem.Drawing.Printing.PrintDocumentprintDoc=
newSystem.Drawing.Printing.PrintDocument();//PrintDocumnetObjectusedforprinting
privatestaticstringPrintTitle="";//Headerofpages
privatestaticDataGridViewdgv;//HoldsDataGridViewObjecttoprintitscontents
privatestaticList<string>SelectedColumns=newList<string>();//TheColumnsSelectedbyusertoprint.
privatestaticList<string>AvailableColumns=newList<string>();//AllColumnsavaiableinDataGrid
privatestaticboolPrintAllRows=true;//True=printallrows,False=printselectedrows
privatestaticboolFitToPageWidth=true;//True=Fitsselectedcolumnstopagewidth,False=Printcolumnsasshowed
privatestaticintHeaderHeight=0;
publicstaticvoidPrint_DataGridView(DataGridViewdgv1)
{
PrintPreviewDialogppvw;
try
{
//GettingDataGridViewobjecttoprint
dgv=dgv1;
//GettingallCoulmnsNamesintheDataGridView
AvailableColumns.Clear();
foreach(DataGridViewColumncindgv.Columns)
{
if(!c.Visible)continue;
AvailableColumns.Add(c.HeaderText);
}
//ShowingthePrintOptionForm
PrintOptionsdlg=newPrintOptions(AvailableColumns);
if(dlg.ShowDialog()!=DialogResult.OK)return;
PrintTitle=dlg.PrintTitle;
PrintAllRows=dlg.PrintAllRows;
FitToPageWidth=dlg.FitToPageWidth;
SelectedColumns=dlg.GetSelectedColumns();
RowsPerPage=0;
ppvw=newPrintPreviewDialog();
ppvw.Document=printDoc;
//ShowingthePrintPreviewPage
printDoc.BeginPrint+=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage+=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
if(ppvw.ShowDialog()!=DialogResult.OK)
{
printDoc.BeginPrint-=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage-=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
return;
}
//PrintingtheDocumnet
printDoc.Print();
printDoc.BeginPrint-=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage-=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
}
}
privatestaticvoidPrintDoc_BeginPrint(objectsender,
System.Drawing.Printing.PrintEventArgse)
{
try
{
//FormattingtheContentofTextCelltoprint
StrFormat=newStringFormat();
StrFormat.Alignment=StringAlignment.Near;
StrFormat.LineAlignment=StringAlignment.Center;
StrFormat.Trimming=StringTrimming.EllipsisCharacter;
//FormattingtheContentofComboCellstoprint
StrFormatComboBox=newStringFormat();
StrFormatComboBox.LineAlignment=StringAlignment.Center;
StrFormatComboBox.FormatFlags=StringFormatFlags.NoWrap;
StrFormatComboBox.Trimming=StringTrimming.EllipsisCharacter;
ColumnLefts.Clear();
ColumnWidths.Clear();
ColumnTypes.Clear();
CellHeight=0;
RowsPerPage=0;
//Forvariouscolumntypes
CellButton=newButton();
CellCheckBox=newCheckBox();
CellComboBox=newComboBox();
//CalculatingTotalWidths
TotalWidth=0;
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))continue;
TotalWidth+=GridCol.Width;
}
PageNo=1;
NewPage=true;
RowPos=0;
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
privatestaticvoidPrintDoc_PrintPage(objectsender,
System.Drawing.Printing.PrintPageEventArgse)
{
inttmpWidth,i;
inttmpTop=e.MarginBounds.Top;
inttmpLeft=e.MarginBounds.Left;
try
{
//Beforestartingfirstpage,itsavesWidth&HeightofHeadersandCoulmnType
if(PageNo==1)
{
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
//Skipifthecurrentcolumnnotselected
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))continue;
//Deteminingwhetherthecolumnsarefittedtopageornot.
if(FitToPageWidth)
tmpWidth=(int)(Math.Floor((double)((double)GridCol.Width/
(double)TotalWidth*(double)TotalWidth*
((double)e.MarginBounds.Width/(double)TotalWidth))));
else
tmpWidth=GridCol.Width;
HeaderHeight=(int)(e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font,tmpWidth).Height)+11;
//Savewidth&heightofheadresandColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
ColumnTypes.Add(GridCol.GetType());
tmpLeft+=tmpWidth;
}
}
//PrintingCurrentPage,RowbyRow
while(RowPos<=dgv.Rows.Count-1)
{
DataGridViewRowGridRow=dgv.Rows[RowPos];
if(GridRow.IsNewRow||(!PrintAllRows&&!GridRow.Selected))
{
RowPos++;
continue;
}
CellHeight=GridRow.Height;
if(tmpTop+CellHeight>=e.MarginBounds.Height+e.MarginBounds.Top)
{
DrawFooter(e,RowsPerPage);
NewPage=true;
PageNo++;
e.HasMorePages=true;
return;
}
else
{
if(NewPage)
{
//DrawHeader
e.Graphics.DrawString(PrintTitle,newFont(dgv.Font,FontStyle.Bold),
Brushes.Black,e.MarginBounds.Left,e.MarginBounds.Top-
e.Graphics.MeasureString(PrintTitle,newFont(dgv.Font,
FontStyle.Bold),e.MarginBounds.Width).Height-13);
Strings=DateTime.Now.ToLongDateString()+""+DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(s,newFont(dgv.Font,FontStyle.Bold),
Brushes.Black,e.MarginBounds.Left+(e.MarginBounds.Width-
e.Graphics.MeasureString(s,newFont(dgv.Font,
FontStyle.Bold),e.MarginBounds.Width).Width),e.MarginBounds.Top-
e.Graphics.MeasureString(PrintTitle,newFont(newFont(dgv.Font,
FontStyle.Bold),FontStyle.Bold),e.MarginBounds.Width).Height-13);
//DrawColumns
tmpTop=e.MarginBounds.Top;
i=0;
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))
continue;
e.Graphics.FillRectangle(newSolidBrush(Color.LightGray),
newRectangle((int)ColumnLefts[i],tmpTop,
(int)ColumnWidths[i],HeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
newRectangle((int)ColumnLefts[i],tmpTop,
(int)ColumnWidths[i],HeaderHeight));
e.Graphics.DrawString(GridCol.HeaderText,GridCol.InheritedStyle.Font,
newSolidBrush(GridCol.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i],tmpTop,
(int)ColumnWidths[i],HeaderHeight),StrFormat);
i++;
}
NewPage=false;
tmpTop+=HeaderHeight;
}
//DrawColumnsContents
i=0;
foreach(DataGridViewCellCelinGridRow.Cells)
{
if(!Cel.OwningColumn.Visible)continue;
if(!SelectedColumns.Contains(Cel.OwningColumn.HeaderText))
continue;
//FortheTextBoxColumn
if(((Type)ColumnTypes[i]).Name=="DataGridViewTextBoxColumn"||
((Type)ColumnTypes[i]).Name=="DataGridViewLinkColumn")
{
e.Graphics.DrawString(Cel.Value.ToString(),Cel.InheritedStyle.Font,
newSolidBrush(Cel.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i],(float)tmpTop,
(int)ColumnWidths[i],(float)CellHeight),StrFormat);
}
//FortheButtonColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewButtonColumn")
{
CellButton.Text=Cel.Value.ToString();
CellButton.Size=newSize((int)ColumnWidths[i],CellHeight);
Bitmapbmp=newBitmap(CellButton.Width,CellButton.Height);
CellButton.DrawToBitmap(bmp,newRectangle(0,0,
bmp.Width,bmp.Height));
e.Graphics.DrawImage(bmp,newPoint((int)ColumnLefts[i],tmpTop));
}
//FortheCheckBoxColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewCheckBoxColumn")
{
CellCheckBox.Size=newSize(14,14);
CellCheckBox.Checked=(bool)Cel.Value;
Bitmapbmp=newBitmap((int)ColumnWidths[i],CellHeight);
GraphicstmpGraphics=Graphics.FromImage(bmp);
tmpGraphics.FillRectangle(Brushes.White,newRectangle(0,0,
bmp.Width,bmp.Height));
CellCheckBox.DrawToBitmap(bmp,
newRectangle((int)((bmp.Width-CellCheckBox.Width)/2),
(int)((bmp.Height-CellCheckBox.Height)/2),
CellCheckBox.Width,CellCheckBox.Height));
e.Graphics.DrawImage(bmp,newPoint((int)ColumnLefts[i],tmpTop));
}
//FortheComboBoxColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewComboBoxColumn")
{
CellComboBox.Size=newSize((int)ColumnWidths[i],CellHeight);
Bitmapbmp=newBitmap(CellComboBox.Width,CellComboBox.Height);
CellComboBox.DrawToBitmap(bmp,newRectangle(0,0,
bmp.Width,bmp.Height));
e.Graphics.DrawImage(bmp,newPoint((int)ColumnLefts[i],tmpTop));
e.Graphics.DrawString(Cel.Value.ToString(),Cel.InheritedStyle.Font,
newSolidBrush(Cel.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i]+1,tmpTop,(int)ColumnWidths[i]
-16,CellHeight),StrFormatComboBox);
}
//FortheImageColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewImageColumn")
{
RectangleCelSize=newRectangle((int)ColumnLefts[i],
tmpTop,(int)ColumnWidths[i],CellHeight);
SizeImgSize=((Image)(Cel.FormattedValue)).Size;
e.Graphics.DrawImage((Image)Cel.FormattedValue,
newRectangle((int)ColumnLefts[i]+(int)((CelSize.Width-ImgSize.Width)/2),
tmpTop+(int)((CelSize.Height-ImgSize.Height)/2),
((Image)(Cel.FormattedValue)).Width,((Image)(Cel.FormattedValue)).Height));
}
//DrawingCellsBorders
e.Graphics.DrawRectangle(Pens.Black,newRectangle((int)ColumnLefts[i],
tmpTop,(int)ColumnWidths[i],CellHeight));
i++;
}
tmpTop+=CellHeight;
}
RowPos++;
//ForthefirstpageitcalculatesRowsperPage
if(PageNo==1)RowsPerPage++;
}
if(RowsPerPage==0)return;
//WriteFooter(PageNumber)
DrawFooter(e,RowsPerPage);
e.HasMorePages=false;
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
privatestaticvoidDrawFooter(System.Drawing.Printing.PrintPageEventArgse,
intRowsPerPage)
{
doublecnt=0;
//Deteminingrowsnumbertoprint
if(PrintAllRows)
{
if(dgv.Rows[dgv.Rows.Count-1].IsNewRow)
cnt=dgv.Rows.Count-2;//WhentheDataGridViewdoesn'tallowaddingrows
else
cnt=dgv.Rows.Count-1;//WhentheDataGridViewallowsaddingrows
}
else
cnt=dgv.SelectedRows.Count;
//WritingthePageNumberontheBottomofPage
stringPageNum="第"+PageNo.ToString()
+"页,共"+Math.Ceiling((double)(cnt/RowsPerPage)).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);
}
}
}
示例工程下载:
testPrint
分享到:
相关推荐
DataGridView打印。打印预览解决方案-第一部分
DataGridView打印。打印预览解决方案-第一部分.zip
本DataGridView打印控件和.NET轻松打印控件5.0版(含报表模板设计组件)2012年5月12日修改完成,完全免费,在.NET2.0及以上环境下都可以使用(VB、C#等都可以用),有帮助文档与使用实例。 与4.95版相比,控件5.0版...
1.vs2008,在解决方案中添加现有项目DLLFullPrint,然后在主工程中添加引用,引用这个项目。 2.在界面设计中,添加按钮PrintButton,双击它进入代码界面; 在代码文件中,首先使用using DLLFullPrint; 然后按钮...
本DataGridView打印控件和.NET打印控件5.6版(含报表模板设计组件)2014年6月22日修改完成,完全免费,在.NET2.0及以上环境下都可以使用(VB打印、C#打印都是可以的),有帮助文档与使用实例。 与上一版本的5.5版...
这个打印解决方案由一个打印设置的窗体,及一个打印类组成。 可用于以下场景: 1、显示的数据量较大,但又没有必要打印全部数据的时候 2、希望打印出的列宽能自动适应页面宽度
1、强大的DataGridView打印功能,不仅可以以多种形式(普通打印、分栏打印、跨页打印、工资条打印)打印DGV表格,基本上能完全按DGV控件本身设置的格式如字体、字号、背景颜色、前景颜色、单元格对齐方式等打印出来...
本DataGridView打印控件和.NET打印控件5.5版(含报表模板设计组件)2014年2月8日修改完成,完全免费,在.NET2.0及以上环境下都可以使用(VB打印、C#打印都是可以的),有帮助文档与使用实例。 与上一版本的5.4版...
本DataGridView打印控件和.NET打印控件5.7版2014年11月2日修改完成,完全免费,在.NET2.0及以上环境下都可以使用(VB打印、C#打印都是可以的),有帮助文档与使用实例。 与上一版相比,控件5.7版的主要更改如下: 1...
一完美的关于请求的目录不存在而需要url重写的解决方案! 在C#中实现MSN消息框的功能 XmlHttp实现无刷新三联动ListBox 鼠标放在一个连接上,会显示图片(类似tooltip) 使用microsoft.web.ui.webcontrols的TabStrip与...
实例001 根据需要创建所需解决方案 实例002 统一窗体中控件的字体设置 实例003 设置程序代码行号 实例004 通过“格式”菜单布局窗体 实例005 为项目添加dll文件引用 实例006 为项目添加已有类 实例007 为项目添加第...
实例001 根据需要创建所需解决方案 2 实例002 统一窗体中控件的字体设置 3 实例003 设置程序代码行号 5 实例004 通过“格式”菜单布局窗体 6 实例005 为项目添加dll文件引用 7 实例006 为项目添加已有类 8 实例007 ...
实例004 根据需要创建所需解决方案 6 1.2 Visual Studio开发环境的使用 8 实例005 为程序设置版本和帮助信息 8 实例006 设置Windows应用程序启动窗体 9 实例007 统一窗体中控件的字体设置 10 实例008 通过“格式”...
1.5.7 解决方案资源管理器窗口 1.5.8 属性窗口 1.5.9 代码编辑器 1.5.10 “错误列表”面板 1.5.11 “输出”面板 1.6 程序调试 1.6.1 断点操作 1.6.2 使用开始、中断和停止执行功能调试程序 1.6.3 单步执行 1.6.4 ...
6.2.3 认识解决方案资源管理器 125 6.2.4 认识服务器资源管理器 128 6.3 本章小结 131 第7章 WinForms窗体介绍 132 7.1 Form窗体 133 7.1.1 Form窗体概述 133 7.1.2 Form窗体的使用 133 7.2 MDI窗体...
1.6.4 项目和解决方案 11 1.6.5 设置Visual C++ 2005的选项 23 1.6.6 创建和执行Windows应用程序 24 1.6.7 创建Windows Forms应用程序 26 1.7 小结 29 第2章 数据、变量和计算 31 2.1 C++程序结构 31 ...