知方号

知方号

C#.NET PrintDocument 自定义报表数据打印<打印报表>

C#.NET PrintDocument 自定义报表数据打印

这是一个自定义的报表打印,是对PrintPreviewDialog的扩展和封装。PrintPreviewDialog是一个windows的打印预览控件,该类返回的就是一个PrintPreviewDialog对象了,直接显示该控件就可以了。

    该报表主要包含两个方面的内容:一个是数据统计分析的饼状图(数据集是用DataTable保存的,,图形统计值分析DataTable的前两列);另一个就是DataTable的数据集了,可以自己定义绘制的格式(当然得自己写代码了)。

    效果预览图如下所示:

    该类的源代码如下:

代码using System; using System.Collections.Generic; using System.Linq;using System.Text;//using System.Drawing;using System.Drawing.Printing;using System.Data;using System.Windows.Forms;//using Microsoft.Office.Interop.Excel;using System.Reflection;namespace WinFormTest{////// 数据报表统计/// ryan-2010/9/19///publicclass DataReprot {#region//property//image sizeint _Width =600;int _Height =420;//pagerprivateint _TopMargin =50;privateint _LeftMargin =60;privateint _RightMargin =50;privateint _BottomMargin =60;private Font _TitleFont =new Font("宋体", 18, FontStyle.Bold);private Font _ColumnsHeaderFont =new Font("宋体", 10, FontStyle.Bold);private Font _ContentFont =new Font("宋体", 9, FontStyle.Regular); SolidBrush brush=new SolidBrush(Color.Black); Pen pen =new Pen(new SolidBrush(Color.Black));int _RowHeight =30;int _CurrentPageIndex;int _PageCount;int _RowsCount;int _CurrentRowsIndex;int _MaxRowsCount =35; Point _CurrentPoint; DataTable _DT;string _Title;string _ImgTitle;string[] _ColumnsHeader;string[] _BottomStr;#endregion#region//DataReprot()public DataReprot(string title, string imgTitle, DataTable dataTable, string[] columnsHeader, string[] bottomStr) { _Title = title; _DT = Sort(dataTable); _ImgTitle = imgTitle; _ColumnsHeader = columnsHeader; _RowsCount = dataTable.Rows.Count; _BottomStr = bottomStr; _CurrentPageIndex =0; _CurrentRowsIndex =0;//pagecountif ((dataTable.Rows.Count +20) % _MaxRowsCount ==0) _PageCount = (dataTable.Rows.Count +20) / _MaxRowsCount;else _PageCount = ((dataTable.Rows.Count +20) / _MaxRowsCount) +1; }#endregion#region//保存为exclpublicvoid SaveAsExcl(string fileFullPath) { Microsoft.Office.Interop.Excel.ApplicationClass excel =new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbook wBook = excel.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Worksheet wSheet = (Microsoft.Office.Interop.Excel.Worksheet)wBook.ActiveSheet; excel.DisplayAlerts =false; excel.AlertBeforeOverwriting =false;// excel.ActiveWorkbook.sav excel.Cells[1, 1] ="网上搜索C#实现excel操作的示例太多了,但不知道有多少是经过验证确实 ";// excel.ActiveWorkbook.SaveCopyAs(fileFullPath); excel.Quit(); }#endregion#region//对dt排序public DataTable Sort(DataTable dataTable) {string orderName = dataTable.Columns[1].ColumnName; DataView dv = dataTable.DefaultView; dv.Sort = orderName +" DESC"; dataTable = dv.ToTable();return dataTable; }#endregion#region//打印报表public PrintPreviewDialog PrintReport() { // PrintDocument printDoc=new PrintDocument(); printDoc.PrintPage+=PrintPage; printDoc.BeginPrint += BeginPrint; PrintPreviewDialog pPreviewDialog =new PrintPreviewDialog(); pPreviewDialog.Document = printDoc; pPreviewDialog.ShowIcon =false; pPreviewDialog.PrintPreviewControl.Zoom =1.0; pPreviewDialog.TopLevel =false; SetPrintPreviewDialog(pPreviewDialog);return pPreviewDialog; }#endregion#region//Bitmap GetPieImage()#region//绘制饼状图////// 绘制饼状图//////public Bitmap GetPieImage(string title, DataTable dataTable) { Bitmap image = GenerateImage(title); dataTable = DataFormat(dataTable);//主区域图形 Rectangle RMain =new Rectangle(35, 70, 380, 300);//图例信息 Rectangle RDes =new Rectangle(445, 90, 10, 10); Font f =new Font("宋体", 10, FontStyle.Regular); Graphics g = Graphics.FromImage(image); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;try {//分析数据,绘制饼图和图例说明double[] ItemRate = GetItemRate(dataTable);int[] ItemAngle = GetItemAngle(ItemRate);int Angle1 =0;int Angle2 =0;int len = ItemRate.Length; Color c =new Color();//3D g.DrawPie(new Pen(Color.Black), RMain, 0F, 360F); g.DrawPie(new Pen(Color.Black), new Rectangle(RMain.X, RMain.Y +10, RMain.Width, RMain.Height), 0F, 360F); g.FillPie(new SolidBrush(Color.Black), new Rectangle(RMain.X, RMain.Y +10, RMain.Width, RMain.Height), 0F, 360F);//绘制for (int i =0; i < len; i++) { Angle2 = ItemAngle[i];//if (c != GetRandomColor(i)) c = GetRandomColor(i); SolidBrush brush =new SolidBrush(c);string DesStr = dataTable.Rows[i][0].ToString() +"("+ (ItemRate[i] *100).ToString(".00") +"%"+")";// DrawPie(image, RMain, c, Angle1, Angle2); Angle1 += Angle2; DrawDes(image, RDes, c, DesStr, f, i); }return image; }finally { g.Dispose(); } }#endregion#region//绘制图像的基本数据计算方法////// 数据格式化///private DataTable DataFormat(DataTable dataTable) {if (dataTable ==null)return dataTable;//把大于等于10的行合并,if (dataTable.Rows.Count 0) x += width; e.Graphics.DrawString(_BottomStr[i], _ContentFont, new SolidBrush(Color.Black), x, y); } x = e.PageBounds.Width - _RightMargin - pageNumWidth; e.Graphics.DrawString(string.Format("第{0}页/共{1}页",_CurrentPageIndex,_PageCount), _ContentFont, new SolidBrush(Color.Black), x, y); }#endregion#region//绘制表格和序号、数据privatevoid DrawTableAndSerialNumAndData(PrintPageEventArgs e, int serialNumWidth, int colWidth) {int useAbleHeight = e.PageBounds.Height - _CurrentPoint.Y - _BottomMargin;int useAbleRowsCount = useAbleHeight / _RowHeight;int rowsCount=0;if (_RowsCount-_CurrentRowsIndex > useAbleRowsCount) rowsCount = useAbleRowsCount;else rowsCount = _RowsCount - _CurrentRowsIndex; Point pp =new Point(_CurrentPoint.X, _CurrentPoint.Y);for(int i=0;i= rowsCount)break; DrawCellString((i +1+ _CurrentRowsIndex).ToString(), pp, serialNumWidth,_ContentFont, e); pp.X += serialNumWidth;for (int j =0; j < _DT.Columns.Count; j++) { DrawCellString(_DT.Rows[i + _CurrentRowsIndex][j].ToString(), pp, colWidth, _ContentFont, e); pp.X += colWidth; } pp.Y += _RowHeight; pp.X = _CurrentPoint.X; }//绘制竖线 Point p =new Point(_CurrentPoint.X,_CurrentPoint.Y); e.Graphics.DrawLine(pen, p, new Point(p.X, p.Y + _RowHeight * rowsCount)); p.X += serialNumWidth; e.Graphics.DrawLine(pen, p, new Point(p.X, p.Y + _RowHeight * rowsCount));for (int i =1; i < _DT.Columns.Count; i++) { p.X += colWidth; e.Graphics.DrawLine(pen, p, new Point(p.X, p.Y + _RowHeight * rowsCount)); } p.X=e.PageBounds.Width-_RightMargin; e.Graphics.DrawLine(pen, p, new Point(p.X, p.Y + _RowHeight * rowsCount)); _CurrentRowsIndex += rowsCount; }#endregion#region//填充数据到单元格privatevoid DrawCellString(string str, Point p,int colWidth,Font f, PrintPageEventArgs e) {int strWidth = (int)e.Graphics.MeasureString(str, f).Width;int strHeight = (int)e.Graphics.MeasureString(str, f).Height; p.X += (colWidth - strWidth) /2; p.Y +=5; p.Y += (_RowHeight - strHeight) /2; e.Graphics.DrawString(str, f, brush, p); }#endregion#region//绘制标题privatevoid DrawTableHeader(PrintPageEventArgs e, int serialNumWidth,int colWidth) {//画框 Point pp =new Point(_CurrentPoint.X, _CurrentPoint.Y); e.Graphics.DrawLine(pen, pp, new Point(e.PageBounds.Width - _RightMargin, pp.Y)); pp.Y+=_RowHeight; e.Graphics.DrawLine(pen,pp,new Point(e.PageBounds.Width-_RightMargin,pp.Y)); pp =new Point(_CurrentPoint.X, _CurrentPoint.Y); e.Graphics.DrawLine(pen, pp, new Point(pp.X, pp.Y + _RowHeight)); pp.X += serialNumWidth; e.Graphics.DrawLine(pen,pp, new Point(pp.X, pp.Y + _RowHeight));for (int i =1; i < _DT.Columns.Count; i++) { pp.X += colWidth; e.Graphics.DrawLine(pen, pp, new Point(pp.X, pp.Y + _RowHeight)); } pp.X = e.PageBounds.Width - _RightMargin; e.Graphics.DrawLine(pen, pp, new Point(pp.X, pp.Y + _RowHeight));// Point p =new Point(_CurrentPoint.X +5, _CurrentPoint.Y); DrawCellString("序号", p, serialNumWidth,_ColumnsHeaderFont, e); p.X += serialNumWidth;for (int i =0; i < _DT.Columns.Count; i++) {if(i!=0) p.X += colWidth; DrawCellString(_ColumnsHeader[i], p, colWidth, _ColumnsHeaderFont, e); } _CurrentPoint.X = _LeftMargin; _CurrentPoint.Y += _RowHeight; }#endregion#region// 自定义设置打印预览对话框publicvoid SetPrintPreviewDialog(PrintPreviewDialog pPreviewDialog) { System.Reflection.PropertyInfo[] pis = pPreviewDialog.GetType().GetProperties(); for (int i =0; i < pis.Length; i++) {switch(pis[i].Name) {case"Dock": pis[i].SetValue(pPreviewDialog, DockStyle.Fill, null);break;case"FormBorderStyle": pis[i].SetValue(pPreviewDialog, FormBorderStyle.None, null);break;case"WindowState": pis[i].SetValue(pPreviewDialog, FormWindowState.Normal, null);break;default:break; } }#region//屏蔽默认的打印按钮,添加自定义的打印和保存按钮foreach (Control c in pPreviewDialog.Controls) {if (c is ToolStrip) { ToolStrip ts = (ToolStrip)c; ts.Items[0].Visible =false;//print ToolStripButton toolStripBtn_Print =new ToolStripButton(); toolStripBtn_Print.Text ="打印"; toolStripBtn_Print.ToolTipText ="打印当前报表数据"; toolStripBtn_Print.Image = Properties.Resources.printer; toolStripBtn_Print.Click +=delegate(object sender, EventArgs e) { PrintDialog pd =new PrintDialog(); pd.Document = pPreviewDialog.Document; pd.UseEXDialog =true;if (pd.ShowDialog() == DialogResult.OK) pPreviewDialog.Document.Print(); }; ToolStripButton toolStripBtn_SaveAsExcel =new ToolStripButton(); toolStripBtn_SaveAsExcel.Text ="保存Excel"; toolStripBtn_SaveAsExcel.ToolTipText ="导出报表到Excel"; toolStripBtn_SaveAsExcel.Image = Properties.Resources.save; toolStripBtn_SaveAsExcel.Click +=delegate(object sender, EventArgs e) { SaveFileDialog f =new SaveFileDialog(); if (f.ShowDialog() == DialogResult.OK) { SaveAsExcl(f.FileName); } }; ToolStripSeparator tss =new ToolStripSeparator(); ts.Items.Insert(0, toolStripBtn_Print); ts.Items.Insert(1, toolStripBtn_SaveAsExcel); ts.Items.Insert(2, tss); } }#endregion }#endregion#endregion } } 代码privatevoid button2_Click(object sender, EventArgs e) { //测试数据 DataTable dataTable =new DataTable(); dataTable.Columns.Add("id", typeof(string)); dataTable.Columns.Add("value1", typeof(double)); dataTable.Columns.Add("value2", typeof(double)); for (int i =0; i

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了