一下这个类专门用于打印DataGridView,但是功能不是很强大 如果有个性化需求 可在此基础上简单修改
Code

1
public class DataGridViewPrint
2
{
3
private DataGridView dataGridView;
4
private PrintDocument printDocument;
5
private PageSetupDialog pageSetupDialog;
6
private PrintPreviewDialog printPreviewDialog;
7
8
public DataGridViewPrint(DataGridView dataGridView)
9
{
10
this.dataGridView = dataGridView;
11
printDocument = new PrintDocument();
12
printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);
13
}
14
15
private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
16
{
17
int rowCount = 0;
18
int colCount = 0;
19
int x = 0;
20
int y = 0;
21
int rowGap = 20;
22
int colGap = 5;
23
int leftMargin = 50;
24
Font font = new Font("Arial", 10);
25
Font headingFont = new Font("Arial", 11, FontStyle.Underline);
26
Font captionFont = new Font("Arial", 10, FontStyle.Bold);
27
Brush brush = new SolidBrush(Color.Black);
28
string cellValue = "";
29
30
if (dataGridView.DataSource.GetType().ToString() == "System.Data.DataTable")
31
{
32
rowCount = ((DataTable)dataGridView.DataSource).Rows.Count;
33
}
34
else if (dataGridView.DataSource.GetType().ToString() == "System.Collections.ArrayList")
35
{
36
rowCount = ((ArrayList)dataGridView.DataSource).Count;
37
}
38
colCount = dataGridView.ColumnCount;
39
40
41
42
43
//print headings
44
y += rowGap;
45
x = leftMargin;
46
for (int j = 0; j < colCount; j++)
47
{
48
if (dataGridView.Columns[j].Width > 0)
49
{
50
cellValue = dataGridView.Columns[j].HeaderText;
51
e.Graphics.DrawString(cellValue, headingFont, brush, x, y);
52
x += dataGridView.Columns[j].Width + colGap;
53
}
54
}
55
56
//print all rows
57
for (int i = 0; i < rowCount; i++)
58
{
59
y += rowGap;
60
x = leftMargin;
61
for (int j = 0; j < colCount; j++)
62
{
63
if (dataGridView.Columns[j].Width > 0)
64
{
65
cellValue = dataGridView[i, j].ToString();
66
e.Graphics.DrawString(cellValue, font, brush, x, y);
67
x += dataGridView.Columns[j].Width + colGap;
68
y = y + rowGap * (cellValue.Split(new char[]
{ ' ', ' ' }).Length - 1);
69
}
70
}
71
}
72
string s = cellValue;
73
string f3 = cellValue;
74
}
75
76
public PrintDocument GetPrintDocument()
77
{
78
return printDocument;
79
}
80
81
public void Print()
82
{
83
try
84
{
85
pageSetupDialog = new PageSetupDialog();
86
pageSetupDialog.Document = printDocument;
87
pageSetupDialog.ShowDialog();
88
printPreviewDialog = new PrintPreviewDialog();
89
printPreviewDialog.Document = printDocument;
90
printPreviewDialog.Height = 600;
91
printPreviewDialog.Width = 800;
92
printPreviewDialog.ShowDialog();
93
}
94
catch (Exception e)
95
{
96
throw new Exception("Printer error." + e.Message);
97
}
98
99
}
100
}