Logo Background RSS

如何在C#中实现DATAGRIDVIEW 数据打印

  • 本文由 秦 涛秦 涛 于 2008年十一月2日 发表在 《C#/.NET
    交流信息: 哇!现在有 2 位大侠指点过了.2 条评论 Comments (520 views)

    分享下关于 C#中 实现打印功能的代码   希望对初学者有所帮助

    关于打印格式感觉很痛苦 我一般选择两种方式 一种是通过 DRAWING 格式,另外一种通过HTML代码来控制,都特别麻烦,不知道各位高手能否提供一些更好的建议?

    第一步 基本操作

    定义 一个C#提供的 PrintDocument 对象

    private PrintDocument printDocument;

    第二步

    //写一个方法 对打印事件进行初始化

    下载: Init.cs
    1. private void PrintDocument()
    2. {
    3. printDocument = new PrintDocument();
    4. printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
    5. }

    第三步

    事件响应方法

    下载: Action.cs
    1. private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
    2. {
    3. //StringReader lineReader = new StringReader(textBox.Text);
    4. Graphics graphic = e.Graphics;//获取绘图对象
    5. float linesPerPage = 0;//页面行号
    6. float yPosition = 0;//绘制字符串的纵向位置
    7. float leftMargin = e.MarginBounds.Left;//左边距
    8. float topMargin = e.MarginBounds.Top;//上边距
    9. string line = string.Empty;//读取的行字符串
    10. int currentPageLine = 0;//当前页读取的行数
    11. Font charFont = button1.Font;//获取打印字体
    12. SolidBrush brush = new SolidBrush(Color.Black);//刷子
    13. linesPerPage = e.MarginBounds.Height / charFont.GetHeight(graphic);//每页可打印的行数
    14. //countNum记录全局行数,currentPageLine记录当前打印页行数。
    15. // graphic.DrawString("水费通知单", charFont, brush, 360, 100, new StringFormat());
    16.  
    17. //房产地址textbox3
    18. //租户名字textbox2
    19. // 上次缴费记录 textbox5
    20. //费用到期 textbox7
    21. //合同开始时间 textbox4
    22. //合同到期时间 textbox6
    23. //月租金 textbox8
    24. //月管理费 textbox9
    25. //缴费租金 textbox11
    26. //缴费管理费 textbox10
    27. //总计   textbox12
    28.  
    29. graphic.DrawString("武大教育发展有限公司房屋租金缴费登记", charFont, brush, 300, 100, new StringFormat());
    30. graphic.DrawString("租户:         " + this.textBox2.Text, charFont, brush, 100, 140, new StringFormat());
    31. graphic.DrawString("合同号:       " + this.textBox1.Text, charFont, brush, 100, 180, new StringFormat());
    32. graphic.DrawString("房产地址:     " + this.textBox3.Text, charFont, brush, 100, 220, new StringFormat());
    33. graphic.DrawString("月租金:       " + this.textBox8.Text, charFont, brush, 100, 260, new StringFormat());
    34. graphic.DrawString("月管理费:     " + this.textBox9.Text, charFont, brush, 100, 300, new StringFormat());
    35. graphic.DrawString("上次缴费至:   " + this.textBox7.Text, charFont, brush, 100, 340, new StringFormat());
    36. graphic.DrawString("本次缴费至:   " + this.dateTimePicker1.Text, charFont, brush, 100, 370, new StringFormat());
    37. graphic.DrawString("租金:         " + this.textBox11.Text, charFont, brush, 100, 410, new StringFormat());
    38. graphic.DrawString("管理费:       " + this.textBox10.Text, charFont, brush, 100, 450, new StringFormat());
    39. graphic.DrawString("合计:         " + this.textBox12.Text, charFont, brush, 100, 490, new StringFormat());
    40. graphic.DrawString("备注:", charFont, brush, 100, 530, new StringFormat());
    41. DateTime today = DateTime.Now;
    42. string day = today.Date.ToString();
    43.  
    44. graphic.DrawString("武大教育发展有限责任公司 " + day, charFont, brush, 580, 1100, new StringFormat());
    45.  
    46. }
    47. 第四步 调用 打印 和预览打印
    48.  
    49. this.PrintDocument();
    50. PrintDialog print = new PrintDialog();
    51. //将初始化后的printDocument赋给print.Document
    52. print.Document = printDocument;
    53.  
    54. try
    55. {
    56. if (print.ShowDialog() == DialogResult.OK)
    57. {
    58. //打印时直接调用PrintDocument的Print方法
    59. printDocument.Print();
    60. }
    61. }
    62. catch (Exception ex)
    63. {
    64. MessageBox.Show("打印出错:" + ex.ToString());
    65. //出错则结束打印过程
    66. printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
    67. }
    68.  
    69. 打印预览
    70.  
    71. PrintPreviewDialog printPreview = new PrintPreviewDialog();
    72. //初始化PrintDocument
    73. this.PrintDocument();
    74. //将初始化后的printDocument赋给print.Document
    75. printPreview.Document = printDocument;
    76. try
    77. {
    78. printPreview.ShowDialog();
    79. }
    80. catch (Exception ex)
    81. {
    82. MessageBox.Show(ex.ToString());
    83. }
    84.  
    85. 打印方法实例
    86.  
    87. using System;
    88. using System.Collections.Generic;
    89. using System.ComponentModel;
    90. using System.Data;
    91. using System.Drawing;
    92. using System.Text;
    93. using System.Windows.Forms;
    94. using System.Drawing.Printing;
    95. using System.IO;
    96.  
    97. /// <summary>
    98. /// 实现DataGridView的打印
    99. /// </summary>
    100. public class PrintDataGridView
    101. {
    102. private static List<DataGridViewCellPrint> CellPrintList = new List<DataGridViewCellPrint>();
    103.  
    104. private static int printRowCount = 0;
    105.  
    106. private static bool IsPrint = true;
    107. private static bool IsRole = true;
    108. private static int PoXTmp = 0;
    109. private static int PoYTmp = 0;
    110. private static int WidthTmp = 0;
    111. private static int HeightTmp = 0;
    112. private static int RowIndex = 0;
    113.  
    114. /// <summary>
    115. /// 打印DataGridView控件
    116. /// </summary>
    117. /// <param name="dataGridView">DataGridView控件</param>
    118. /// <param name="includeColumnText">是否包括列标题</param>
    119. /// <param name="e">为 System.Drawing.Printing.PrintDocument.PrintPage 事件提供数据。</param>
    120. /// <param name="PoX">起始X坐标</param>
    121. /// <param name="PoY">起始Y坐标</param>
    122. public static void Print(DataGridView dataGridView, bool includeColumnText, PrintPageEventArgs e, ref int PoX, ref int PoY, string pageTitle)
    123. {
    124. try
    125. {
    126. if (PrintDataGridView.IsPrint)
    127. {
    128. PrintDataGridView.printRowCount = 0;
    129. PrintDataGridView.IsPrint = false;
    130. PrintDataGridView.DataGridViewCellVsList(dataGridView, includeColumnText);
    131. if (0 == PrintDataGridView.CellPrintList.Count)
    132. return;
    133. if (PoX > e.MarginBounds.Left)
    134. PrintDataGridView.IsRole = true;
    135. else
    136. PrintDataGridView.IsRole = false;
    137. PrintDataGridView.PoXTmp = PoX;
    138. PrintDataGridView.PoYTmp = PoY;
    139. PrintDataGridView.RowIndex = 0;
    140. WidthTmp = 0;
    141. HeightTmp = 0;
    142. }
    143. if (0 != PrintDataGridView.printRowCount)
    144. {
    145. if (IsRole)
    146. {
    147. PoX = PoXTmp = e.MarginBounds.Left;
    148. PoY = PoYTmp = e.MarginBounds.Top;
    149. }
    150. else
    151. {
    152. PoX = PoXTmp;
    153. PoY = PoYTmp;
    154. }
    155. }
    156. while (PrintDataGridView.printRowCount < PrintDataGridView.CellPrintList.Count)
    157. {
    158. DataGridViewCellPrint CellPrint = CellPrintList[PrintDataGridView.printRowCount];
    159. if (RowIndex == CellPrint.RowIndex)
    160. PoX = PoX + WidthTmp;
    161. else
    162. {
    163. PoX = PoXTmp;
    164. PoY = PoY + HeightTmp;
    165. if (PoY + HeightTmp > e.MarginBounds.Bottom)
    166. {
    167. HeightTmp = 0;
    168. e.HasMorePages = true;
    169. return;
    170. }
    171. }
    172. using (SolidBrush solidBrush = new SolidBrush(CellPrint.BackColor))
    173. {
    174.  
    175. RectangleF rectF1 = new RectangleF(PoX, PoY, CellPrint.Width, CellPrint.Height);
    176. e.Graphics.FillRectangle(solidBrush, rectF1);
    177. using (Pen pen = new Pen(Color.Black, 1))
    178. {
    179.  
    180. e.Graphics.DrawRectangle(pen, Rectangle.Round(rectF1));
    181. } solidBrush.Color = CellPrint.ForeColor;
    182. //打印 页面标题
    183. e.Graphics.DrawString(pageTitle, CellPrint.Font, solidBrush, 300, 80);
    184. DateTime dt = new DateTime();
    185.  
    186. e.Graphics.DrawString("武大教育发展有限公司 " + dt.Date.ToString(), CellPrint.Font, solidBrush, 400, 1100);
    187. e.Graphics.DrawString(CellPrint.FormattedValue, CellPrint.Font, solidBrush, new Point(PoX + 2, PoY + 3));
    188. }
    189. WidthTmp = CellPrint.Width;
    190. HeightTmp = CellPrint.Height;
    191. RowIndex = CellPrint.RowIndex;
    192. PrintDataGridView.printRowCount++;
    193. }
    194. PoY = PoY + HeightTmp;
    195. e.HasMorePages = false;
    196. PrintDataGridView.IsPrint = true;
    197. }
    198. catch
    199. {
    200. e.HasMorePages = false;
    201. PrintDataGridView.IsPrint = true;
    202. throw;
    203. }
    204.  
    205. }
    206.  
    207. /// <summary>
    208. /// 将DataGridView控件内容转变到 CellPrintList
    209. /// </summary>
    210. /// <param name="dataGridView">DataGridView控件</param>
    211. /// <param name="includeColumnText">是否包括列标题</param>
    212. private static void DataGridViewCellVsList(DataGridView dataGridView, bool includeColumnText)
    213. {
    214. CellPrintList.Clear();
    215. try
    216. {
    217. int rowsCount = dataGridView.Rows.Count;
    218. int colsCount = dataGridView.Columns.Count;
    219.  
    220. //最后一行是供输入的行时,不用读数据。
    221. if (dataGridView.Rows[rowsCount - 1].IsNewRow)
    222. rowsCount--;
    223. //包括列标题
    224. if (includeColumnText)
    225. {
    226. for (int columnsIndex = 0; columnsIndex < colsCount; columnsIndex++)
    227. {
    228. if (dataGridView.Columns[columnsIndex].Visible)
    229. {
    230. DataGridViewCellPrint CellPrint = new DataGridViewCellPrint();
    231. CellPrint.FormattedValue = dataGridView.Columns[columnsIndex].HeaderText;
    232. CellPrint.RowIndex = 0;
    233. CellPrint.ColumnIndex = columnsIndex;
    234. CellPrint.Font = dataGridView.Columns[columnsIndex].HeaderCell.Style.Font;
    235. CellPrint.BackColor = dataGridView.ColumnHeadersDefaultCellStyle.BackColor;
    236. CellPrint.ForeColor = dataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
    237. CellPrint.Width = dataGridView.Columns[columnsIndex].Width;
    238. CellPrint.Height = dataGridView.ColumnHeadersHeight;
    239. CellPrintList.Add(CellPrint);
    240. }
    241. }
    242. }
    243. //读取单元格数据
    244. for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++)
    245. {
    246. for (int columnsIndex = 0; columnsIndex < colsCount; columnsIndex++)
    247. {
    248. if (dataGridView.Columns[columnsIndex].Visible)
    249. {
    250. DataGridViewCellPrint CellPrint = new DataGridViewCellPrint();
    251. CellPrint.FormattedValue = dataGridView.Rows[rowIndex].Cells[columnsIndex].FormattedValue.ToString();
    252. if (includeColumnText)
    253. CellPrint.RowIndex = rowIndex + 1;//假如包括列标题则从行号1开始
    254. else
    255. CellPrint.RowIndex = rowIndex;
    256. CellPrint.ColumnIndex = columnsIndex;
    257. CellPrint.Font = dataGridView.Rows[rowIndex].Cells[columnsIndex].Style.Font;
    258. System.Drawing.Color TmpColor = System.Drawing.Color.Empty;
    259. if (System.Drawing.Color.Empty != dataGridView.Rows[rowIndex].Cells[columnsIndex].Style.BackColor)
    260. TmpColor = dataGridView.Rows[rowIndex].Cells[columnsIndex].Style.BackColor;
    261. else if (System.Drawing.Color.Empty != dataGridView.Rows[rowIndex].DefaultCellStyle.BackColor)
    262. TmpColor = dataGridView.Rows[rowIndex].DefaultCellStyle.BackColor;
    263. else
    264. TmpColor = dataGridView.DefaultCellStyle.BackColor;
    265. CellPrint.BackColor = TmpColor;
    266. TmpColor = System.Drawing.Color.Empty;
    267. if (System.Drawing.Color.Empty != dataGridView.Rows[rowIndex].Cells[columnsIndex].Style.ForeColor)
    268. TmpColor = dataGridView.Rows[rowIndex].Cells[columnsIndex].Style.ForeColor;
    269. else if (System.Drawing.Color.Empty != dataGridView.Rows[rowIndex].DefaultCellStyle.ForeColor)
    270. TmpColor = dataGridView.Rows[rowIndex].DefaultCellStyle.ForeColor;
    271. else
    272. TmpColor = dataGridView.DefaultCellStyle.ForeColor;
    273. CellPrint.ForeColor = TmpColor;
    274. CellPrint.Width = dataGridView.Columns[columnsIndex].Width;
    275. CellPrint.Height = dataGridView.Rows[rowIndex].Height;
    276. CellPrintList.Add(CellPrint);
    277. }
    278. }
    279. }
    280. }
    281. catch { throw; }
    282. }
    283.  
    284. private class DataGridViewCellPrint
    285. {
    286. private string _FormattedValue = "";
    287. private int _RowIndex = -1;
    288. private int _ColumnIndex = -1;
    289. private System.Drawing.Color _ForeColor = System.Drawing.Color.Black;
    290. private System.Drawing.Color _BackColor = System.Drawing.Color.White;
    291. private int _Width = 100;
    292. private int _Height = 23;
    293. private System.Drawing.Font _Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
    294. /// <summary>
    295. /// 获取或设置单元格的字体。
    296. /// </summary>
    297. public System.Drawing.Font Font
    298. {
    299. set { if (null != value) _Font = value; }
    300. get { return _Font; }
    301. }
    302. /// <summary>
    303. /// 获取为显示进行格式化的单元格的值。
    304. /// </summary>
    305. public string FormattedValue
    306. {
    307. set { _FormattedValue = value; }
    308. get { return _FormattedValue; }
    309. }
    310. /// <summary>
    311. /// 获取或设置列的当前宽度 (以像素为单位)。默认值为 100。
    312. /// </summary>
    313. public int Width
    314. {
    315. set { _Width = value; }
    316. get { return _Width; }
    317. }
    318. /// <summary>
    319. /// 获取或设置列标题行的高度(以像素为单位)。默认值为 23。
    320. /// </summary>
    321. public int Height
    322. {
    323. set { _Height = value; }
    324. get { return _Height; }
    325. }
    326. /// <summary>
    327. /// 获取或设置行号。
    328. /// </summary>
    329. public int RowIndex
    330. {
    331. set { _RowIndex = value; }
    332. get { return _RowIndex; }
    333. }
    334. /// <summary>
    335. /// 获取或设置列号。
    336. /// </summary>
    337. public int ColumnIndex
    338. {
    339. set { _ColumnIndex = value; }
    340. get { return _ColumnIndex; }
    341. }
    342. /// <summary>
    343. /// 获取或设置前景色。
    344. /// </summary>
    345. public System.Drawing.Color ForeColor
    346. {
    347. set { _ForeColor = value; }
    348. get { return _ForeColor; }
    349. }
    350. /// <summary>
    351. /// 获取或设置背景色。
    352. /// </summary>
    353. public System.Drawing.Color BackColor
    354. {
    355. set { _BackColor = value; }
    356. get { return _BackColor; }
    357. }
    358.  
    359. }
    360. }
  • 我们的说明!

    欢迎转载,但请您以链接形式注明本文出处和本站原文链接,下面是链接形式,谢谢合作!
    出处链接:Allove of Paradise
    原文链接:http://blog.allove.org/archives/c-sharp-datagridview-print.html
2 条评论
  1. #1 Yacca
    十一月 13th, 2008 at 10:03 上午

    “不想我吗?!”
    里面的东西应该默认显示才对…

    [回复]

    Daniel Reply:

    希望这样用户体验更好!

    [回复]

    Post ReplyPost Reply
Leave a Comment