列印DataGridView中的內容
今天,一個在澳洲工作的朋友在MSN上問我,DataGridView怎麼實現列印功能,由於很久不寫程式碼了,我在網上搜了一下簡單整理一下實現了DataGridView的列印功能。程式碼如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Data;
using System.Text;
namespace DgPrint
{
public class PrintService
{
private StringFormat StrFormat; // Holds content of a TextBox Cell to write by DrawString
private int RowPos;
// Position of currentlyprinting row
private bool NewPage;
// Indicates if a new page reached
private int PageNo;
// Number of pages to print
private int CellHeight;
// Height of DataGrid Cell
private int RowsPerPage;
// Number of Rows per Page
private System.Drawing.Printing.PrintDocument printDoc =
new System.Drawing.Printing.PrintDocument(); // PrintDocumnet Object used for printing
private ArrayList ColumnLefts = new ArrayList(); // Left Coordinate of Columns
private ArrayList ColumnWidths = new ArrayList(); // Width of Columns
private string PrintTitle = ""; // Header of pages
private DataTable dgv;
// Holds DataGridView Object to print its contents
private List
private int HeaderHeight = 0;
private Dictionary
public void Print(DataTable tab, string Title, Dictionary
{
PrintPreviewDialog ppvw;
try
{
// Getting DataGridView object to print
dgv = tab;
ColWith = colWith;
// Getting all Coulmns Names in the DataGridView
AvailableColumns.Clear();
foreach (DataColumn c in dgv.Columns)
{
AvailableColumns.Add(c.ColumnName);
}
// Showing the PrintOption Form
PrintTitle = Title;
RowsPerPage = 0;
printDoc.DocumentName = " ";
PrintDialog dia = new PrintDialog();
dia.PrintToFile = false;
dia.Document = printDoc;
dia.UseEXDialog = true;
if (dia.ShowDialog() != DialogResult.OK) return;
ppvw = new PrintPreviewDialog();
ppvw.WindowState = FormWindowState.Maximized;
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
printDoc.Print();
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
}
catch (Exception ex)
{
}
finally
{
}
}
private DataGridView grid;
public void Print(DataGridView grid, string Title)
{
PrintPreviewDialog ppvw;
try
{
// Getting DataGridView object to print
this.grid = grid;
// Getting all Coulmns Names in the DataGridView
AvailableColumns.Clear();
foreach (DataGridViewColumn c in grid.Columns)
{
if (c.Visible)
AvailableColumns.Add(c.HeaderText);
}
// Showing the PrintOption Form
PrintTitle = Title;
RowsPerPage = 0;
printDoc.DocumentName = " ";
PrintDialog dia = new PrintDialog();
dia.PrintToFile = false;
dia.Document = printDoc;
dia.UseEXDialog = true;
if (dia.ShowDialog() != DialogResult.OK) return;
ppvw = new PrintPreviewDialog();
ppvw.WindowState = FormWindowState.Maximized;
ppvw.Document = printDoc;
// Showing the Print Preview Page
printDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
if (ppvw.ShowDialog() != DialogResult.OK)
{
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
return;
}
// Printing the Documnet
printDoc.Print();
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
}
catch (Exception ex)
{
}
finally
{
}
}
private void PrintGridDoc_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
try
{
StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Near;
StrFormat.LineAlignment = StringAlignment.Center;
StrFormat.Trimming = StringTrimming.EllipsisCharacter;
ColumnLefts.Clear();
ColumnWidths.Clear();
CellHeight = 0;
RowsPerPage = 0;
PageNo = 1;
NewPage = true;
RowPos = 0;
}
catch (Exception ex)
{
}
}
private void PrintGridDoc_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
int tmpWidth, i;
int tmpTop = e.MarginBounds.Top;
int tmpLeft = e.MarginBounds.Left;
Font font = new Font("宋體", 9);
try
{
// Before starting first page, it saves Width & Height of Headers and CoulmnType
if (PageNo == 1)
{
foreach (DataGridViewColumn GridCol in grid.Columns)
{
// Skip if the current column not selected
// Detemining whether the columns are fitted to page or not.
if (GridCol.Visible)
{
tmpWidth = GridCol.Width;
HeaderHeight = 33;
// Save width & height of headres and ColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
tmpLeft += tmpWidth;
}
}
}
// Printing Current Page, Row by Row
while (RowPos <= grid.Rows.Count - 1)
{
DataGridViewRow GridRow = grid.Rows[RowPos];
CellHeight = 22;
if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
DrawGridFooter(e, RowsPerPage);
NewPage = true;
PageNo++;
e.HasMorePages = true;
return;
}
else
{
if (NewPage)
{
// Draw Header
e.Graphics.DrawString(PrintTitle, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(s, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(s, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(new Font(font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
// Draw Columns
tmpTop = e.MarginBounds.Top;
i = 0;
foreach (DataGridViewColumn GridCol in grid.Columns)
{
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, font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight), StrFormat);
i++;
}
NewPage = false;
tmpTop += HeaderHeight;
}
// Draw Columns Contents
i = 0;
foreach (DataGridViewCell Cel in GridRow.Cells)
{
e.Graphics.DrawString(Cel.Value.ToString(), font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], (float)tmpTop,
(int)ColumnWidths[i], (float)CellHeight), StrFormat);
// Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
tmpTop, (int)ColumnWidths[i], CellHeight));
i++;
}
tmpTop += CellHeight;
}
RowPos++;
// For the first page it calculates Rows per Page
if (PageNo == 1) RowsPerPage++;
}
if (RowsPerPage == 0) return;
// Write Footer (Page Number)
DrawGridFooter(e, RowsPerPage);
e.HasMorePages = false;
printDoc.DocumentName = PrintTitle;
}
catch (Exception ex)
{
}
}
private void DrawGridFooter(System.Drawing.Printing.PrintPageEventArgs e,
int RowsPerPage)
{
double cnt = 0;
cnt = grid.Rows.Count; // When the DataGridView allows adding rows
// Writing the Page Number on the Bottom of Page
string PageNum = " 第 " + PageNo.ToString()
+ " 頁,共 " + Math.Ceiling((double)(cnt / RowsPerPage)).ToString()
+ " 頁";
Font font = new Font("宋體", 9);
e.Graphics.DrawString(PageNum, font, Brushes.Black,
e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(PageNum, font,
e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
e.MarginBounds.Height + 31);
}
private void PrintDoc_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
try
{
StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Near;
StrFormat.LineAlignment = StringAlignment.Center;
StrFormat.Trimming = StringTrimming.EllipsisCharacter;
ColumnLefts.Clear();
ColumnWidths.Clear();
CellHeight = 0;
RowsPerPage = 0;
PageNo = 1;
NewPage = true;
RowPos = 0;
}
catch (Exception ex)
{
}
}
private void PrintDoc_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
int tmpWidth, i;
int tmpTop = e.MarginBounds.Top;
int tmpLeft = e.MarginBounds.Left;
Font font = new Font("宋體", 9);
try
{
// Before starting first page, it saves Width & Height of Headers and CoulmnType
if (PageNo == 1)
{
foreach (DataColumn GridCol in dgv.Columns)
{
// Skip if the current column not selected
// Detemining whether the columns are fitted to page or not.
if (ColWith.ContainsKey(GridCol.ColumnName))
tmpWidth = ColWith[GridCol.ColumnName];
else
tmpWidth = 100;
HeaderHeight = 33;
// Save width & height of headres and ColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
tmpLeft += tmpWidth;
}
}
// Printing Current Page, Row by Row
while (RowPos <= dgv.Rows.Count - 1)
{
DataRow GridRow = dgv.Rows[RowPos];
CellHeight = 22;
if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
DrawFooter(e, RowsPerPage);
NewPage = true;
PageNo++;
e.HasMorePages = true;
return;
}
else
{
if (NewPage)
{
// Draw Header
e.Graphics.DrawString(PrintTitle, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(s, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(s, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(new Font(font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
// Draw Columns
tmpTop = e.MarginBounds.Top;
i = 0;
foreach (DataColumn GridCol in dgv.Columns)
{
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.ColumnName, font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight), StrFormat);
i++;
}
NewPage = false;
tmpTop += HeaderHeight;
}
// Draw Columns Contents
i = 0;
foreach (Object Cel in GridRow.ItemArray)
{
e.Graphics.DrawString(Cel.ToString(), font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], (float)tmpTop,
(int)ColumnWidths[i], (float)CellHeight), StrFormat);
// Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
tmpTop, (int)ColumnWidths[i], CellHeight));
i++;
}
tmpTop += CellHeight;
}
RowPos++;
// For the first page it calculates Rows per Page
if (PageNo == 1) RowsPerPage++;
}
if (RowsPerPage == 0) return;
// Write Footer (Page Number)
DrawFooter(e, RowsPerPage);
e.HasMorePages = false;
printDoc.DocumentName = PrintTitle;
}
catch (Exception ex)
{
}
}
private void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e,
int RowsPerPage)
{
double cnt = 0;
cnt = dgv.Rows.Count; // When the DataGridView allows adding rows
// Writing the Page Number on the Bottom of Page
string PageNum = " 第 " + PageNo.ToString()
+ " 頁,共 " + Math.Ceiling((double)(cnt / RowsPerPage)).ToString()
+ " 頁";
Font font = new Font("宋體", 9);
e.Graphics.DrawString(PageNum, font, Brushes.Black,
e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(PageNum, font,
e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
e.MarginBounds.Height + 31);
}
}
}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-610890/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- JavaScript 列印div內容JavaScript
- 將dataGridView內容匯出到Excel檔案ViewExcel
- DatagridView內容換行適應列寬View
- css控制列印內容的樣式CSS
- DataGridView設定單元格的提示內容ToolTip詳解View
- C#將Excel檔案中選擇的內容,複製貼上到 winform datagridviewC#ExcelORMView
- js直接列印pdf檔案內容JS
- 用python寫一個指令碼,讀取srt檔案中的內容,並列印出重複的內容,且將不重複的內容儲存到新檔案中Python指令碼
- gcc編譯階段列印巨集定義的內容GC編譯
- (C語言)使用指標列印陣列的內容C語言指標陣列
- div中的內容居中
- .Net DataGridView列印專家元件使用手冊View元件
- 如何為要被列印的內容設定CSS樣式屬性CSS
- DataGridView列印專家元件終於釋出啦View元件
- HTML API + CSS 控制頁面列印內容和樣式HTMLAPICSS
- DataGridView選中整行View
- jQuery中的常用內容總結(二)jQuery
- jQuery中的常用內容總結(三)jQuery
- jQuery中的常用內容總結(一)jQuery
- Linux基礎命令---echo列印內容到標準輸出Linux
- 印表機列印出來只有一半內容解決教程
- excel怎麼列印到一張a4紙 如何把excel內容列印在一張紙上Excel
- 資料與內容中臺
- javascript 獲取iframe中內容JavaScript
- 給Winform中的datagridview新增行號ORMView
- 使用Mybatis外掛列印SQL詳細內容及執行時間MyBatisSQL
- Springcloud學習筆記62---log.error()列印內容區別SpringGCCloud筆記Error
- 如何解析word文件中的公式內容公式
- Python如何刪除csv中的內容Python
- 修改所有xml檔案中的某些內容XML
- css input文字框中的內容居中效果CSS
- php中抓取網頁內容的程式碼PHP網頁
- javascript如何替換字串中的指定內容JavaScript字串
- js替換字串中的所有指定內容JS字串
- 使用jquery清空指定元素中的所有內容jQuery
- 檢視oracle中controlfile的內容Oracle
- v$lock.type中的內容解釋
- JQuery中判斷元素中是否有內容jQuery