C#操作Word打印的示例
更新时间:2020年12月8日 11:34 点击:1944
话不多说,解释在代码注释中……
class PrintClass { #region 全局变量 private DataGridView datagrid;//需要打印的数据来源 private PageSetupDialog pagesetupdialog; private PrintPreviewDialog printpreviewdialog; int currentpageindex = 0;//当前页的编号 int rowcount = 0;//数据的行数 public Size PaperSize = new Size(827, 1169);//答应的纸张大小 public int headerheight = 30;//标题高度 Margins margins = new Margins(50, 60, 50, 80); public int celltopmargin = 6;//单元格顶边距 public int pagerowcount = 7;//每页行数 public int rowgap = 23;//行高 public int colgap = 5;//每列间隔 public Font headerfont = new Font("Arial", 9, FontStyle.Bold);//列名标题字体 public Brush brushHeaderFont = new SolidBrush(Color.Black);//列名字体画刷 public Font Cellfont = new Font("Arial", 9);//单元格字体 public bool isautopagerowcount = true;//是否自动计算行数 public bool PageAspect = false;//打印的方向 public static bool PageScape = false;//打印方向 public string paperName = string.Empty; #endregion #region 打印信息的初始化 /// <summary> /// 打印信息的初始化 /// </summary> /// <param datagrid="DataGridView">打印数据</param> /// <param PageS="int">纸张大小</param> /// <param lendscape="bool">是否横向打印</param> public PrintClass(DataGridView datagrid, string paperName, bool lendscape) { this.datagrid = datagrid;//获取打印数据 this.paperName = paperName; PrintDocument printdocument = new PrintDocument();//实例化PrintDocument类 printpreviewdialog = new PrintPreviewDialog();//实例化PrintPreviewDialog类 printpreviewdialog.Document = printdocument;//获取预览文档的信息 printpreviewdialog.FormBorderStyle = FormBorderStyle.Fixed3D;//设置窗体的边框样式 //横向打印的设置 if (!string.IsNullOrEmpty(paperName) ) { if (lendscape == true) { printdocument.DefaultPageSettings.Landscape = lendscape;//横向打印 } else { printdocument.DefaultPageSettings.Landscape = lendscape;//纵向打印 } } pagesetupdialog = new PageSetupDialog();//实例化PageSetupDialog类 pagesetupdialog.Document = printdocument;//获取当前页的设置 printdocument.PrintPage += new PrintPageEventHandler(this.printdocument_printpage);//事件的重载 } #endregion #region 页的打印事件 /// <summary> /// 页的打印事件(主要用于绘制打印报表) /// </summary> private void printdocument_printpage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { if (this.isautopagerowcount)//自动计算页的行数 { double countHeight = e.PageBounds.Height - this.margins.Top - this.headerfont.Height - this.headerheight - this.margins.Bottom; pagerowcount = (int)Math.Ceiling(countHeight / this.rowgap);//获取每页的行数 } int pagecount = (int)(rowcount / pagerowcount);//获取打印多少页 pagesetupdialog.AllowOrientation = true;//启动打印页面对话框的方向部分 int colcount = 0;//记录数据的列数 int y = margins.Top;//获取表格的顶边距 string cellvalue = "";//记录文本信息(单元格的文本信息) int startrow = currentpageindex * pagerowcount;//设置打印的初始页数 int endrow = startrow + this.pagerowcount < rowcount ? startrow + pagerowcount : rowcount;//设置打印的最大页数 int currentpagerowcount = endrow - startrow;//获取打印页数 colcount = datagrid.ColumnCount;//获取打印数据的列数 int x = margins.Left;//获取表格的左边距 绘画时的x轴位置 //获取报表的宽度 int cwidth = 0; for (int j = 0; j < colcount; j++)//循环数据的列数 { if (datagrid.Columns[j].Width > 0)//如果列的宽大于0 { cwidth += datagrid.Columns[j].Width + colgap;//累加每列的宽度 } } y += rowgap;//设置表格的上边线的位置 //设置标题栏中的文字 for (int j = 0; j < colcount; j++)//遍历列数据 { int colwidth = datagrid.Columns[j].Width;//获取列的宽度 if (colwidth > 0)//如果列的宽度大于0 { cellvalue = datagrid.Columns[j].HeaderText;//获取列标题 //绘制标题栏文字 e.Graphics.DrawString(cellvalue, headerfont, brushHeaderFont, x, y + celltopmargin);//绘制列标题 x += colwidth + colgap;//横向,下一个单元格的位置 int nnp = y + currentpagerowcount * rowgap + this.headerheight;//下一行线的位置 } } //打印所有的行信息 for (int i = startrow; i < endrow; i++) //对行进行循环 { x = margins.Left; //获取线的X坐标点 for (int j = 0; j < colcount; j++)//对列进行循环 { if (datagrid.Columns[j].Width > 0)//如果列的宽度大于0 { cellvalue = datagrid.Rows[i].Cells[j].Value.ToString();//获取单元格的值 e.Graphics.DrawString(cellvalue, Cellfont, brushHeaderFont, x, y + celltopmargin+rowgap);//绘制单元格信息 x += datagrid.Columns[j].Width + colgap;//单元格信息的X坐标 y = y + rowgap * (cellvalue.Split(new char[] { '\r', '\n' }).Length - 1);//单元格信息的Y坐标 } } y += rowgap;//设置下行的位置 } currentpageindex++;//下一页的页码 if (currentpageindex < pagecount)//如果当前页不是最后一页 { e.HasMorePages = true;//打印副页 } else { e.HasMorePages = false;//不打印副页 this.currentpageindex = 0;//当前打印的页编号设为0 } } #endregion #region 显示打印预览窗体 /// <summary> /// 显示打印预览窗体 /// </summary> public void print() { rowcount = 0;//记录数据的行数 PageSettings storePageSetting = new PageSettings();//实列化一个对PageSettings对象 PrintDocument printdocument = pagesetupdialog.Document; foreach (PaperSize ps in printdocument.PrinterSettings.PaperSizes)//查找当前设置纸张 { if (paperName == ps.PaperName)//如果找到当前纸张的名称 { printdocument.DefaultPageSettings.PaperSize = ps;//获取当前纸张的信息 } } if (datagrid.DataSource is System.Data.DataTable)//判断数据类型 { rowcount = ((DataTable)datagrid.DataSource).Rows.Count;//获取数据的行数 } else if (datagrid.DataSource is System.Collections.ArrayList)//判断数据类型 { rowcount = ((ArrayList)datagrid.DataSource).Count;//获取数据的行数 } try { printdocument.DefaultPageSettings.Landscape = PageScape;//设置横向打印 printpreviewdialog.ShowDialog();//显示打印预览窗体 } catch (Exception e) { throw new Exception("printer error." + e.Message); } } #endregion }
创建一个打印窗体
设计页面代码:
/// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label8 = new System.Windows.Forms.Label(); this.comboBox_PageSize = new System.Windows.Forms.ComboBox(); this.button_Preview = new System.Windows.Forms.Button(); this.checkBox_Aspect = new System.Windows.Forms.CheckBox(); this.panel_Line = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(3, 4); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowTemplate.Height = 23; this.dataGridView1.Size = new System.Drawing.Size(1079, 578); this.dataGridView1.TabIndex = 0; // // groupBox1 // this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.comboBox_PageSize); this.groupBox1.Controls.Add(this.button_Preview); this.groupBox1.Controls.Add(this.checkBox_Aspect); this.groupBox1.Controls.Add(this.panel_Line); this.groupBox1.Location = new System.Drawing.Point(1088, 4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(144, 287); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "打印设置"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(2, 232); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(65, 12); this.label8.TabIndex = 19; this.label8.Text = "纸张大小:"; // // comboBox_PageSize // this.comboBox_PageSize.FormattingEnabled = true; this.comboBox_PageSize.Items.AddRange(new object[] { "A4", "A5", "A6", "B5 (JIS)", "B5", "16K"}); this.comboBox_PageSize.Location = new System.Drawing.Point(67, 229); this.comboBox_PageSize.Name = "comboBox_PageSize"; this.comboBox_PageSize.Size = new System.Drawing.Size(71, 20); this.comboBox_PageSize.TabIndex = 18; // // button_Preview // this.button_Preview.Location = new System.Drawing.Point(34, 254); this.button_Preview.Name = "button_Preview"; this.button_Preview.Size = new System.Drawing.Size(70, 23); this.button_Preview.TabIndex = 17; this.button_Preview.Text = "打印预览"; this.button_Preview.UseVisualStyleBackColor = true; this.button_Preview.Click += new System.EventHandler(this.button_Preview_Click); // // checkBox_Aspect // this.checkBox_Aspect.AutoSize = true; this.checkBox_Aspect.Location = new System.Drawing.Point(34, 211); this.checkBox_Aspect.Name = "checkBox_Aspect"; this.checkBox_Aspect.Size = new System.Drawing.Size(72, 16); this.checkBox_Aspect.TabIndex = 15; this.checkBox_Aspect.Text = "横向打印"; this.checkBox_Aspect.UseVisualStyleBackColor = true; this.checkBox_Aspect.MouseDown += new System.Windows.Forms.MouseEventHandler(this.checkBox_Aspect_MouseDown); // // panel_Line // this.panel_Line.BackColor = System.Drawing.SystemColors.ButtonHighlight; this.panel_Line.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel_Line.Location = new System.Drawing.Point(23, 74); this.panel_Line.Name = "panel_Line"; this.panel_Line.Size = new System.Drawing.Size(100, 116); this.panel_Line.TabIndex = 6; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1234, 594); this.Controls.Add(this.groupBox1); this.Controls.Add(this.dataGridView1); this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "自定义横向或纵向打印"; this.Activated += new System.EventHandler(this.Form1_Activated); this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); }
操作代码:
public bool Aspect = true;//打印方向 public bool boundary = false;//是否打印分割线 private void Form1_Activated(object sender, EventArgs e) { //在窗体中绘制一个预览表格 Graphics g = panel_Line.CreateGraphics(); int paneW = panel_Line.Width;//设置表格的宽度 int paneH = panel_Line.Height;//设置表格的高度 g.DrawRectangle(new Pen(Color.WhiteSmoke, paneW), 0, 0, paneW, paneH);//绘制一个矩形 } private void Form1_Load(object sender, EventArgs e) { comboBox_PageSize.SelectedIndex = 0; OleDbConnection oledbCon = new OleDbConnection(" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Lenovo\\Desktop\\SnapShot.mdb;"); OleDbDataAdapter oledbDa = new OleDbDataAdapter("select * from RegionInfo", oledbCon); DataSet myds = new DataSet(); oledbDa.Fill(myds); dataGridView1.DataSource = myds.Tables[0]; } private void checkBox_Aspect_MouseDown(object sender, MouseEventArgs e) { //改变窗体中预览表格的方向 int aspX = 0;//宽度 int aspY = 0;//高度 if (((CheckBox)sender).Checked == false)//如果不是纵向打印 { aspX = 136;//设置大小 aspY = 98; PrintClass.PageScape = true;//横向打印 } else { aspX = 100;//设置大小 aspY = 116; PrintClass.PageScape = false;//纵向打印 } panel_Line.Width = aspX;//设置控件的宽度 panel_Line.Height = aspY;//设置控件的高度 aspX = (int)((groupBox1.Width - aspX) / 2);//设置控件的Top panel_Line.Location = new Point(aspX, 90);//设置控件的位置 Form1_Activated(sender, e);//设用Activated事件 } private void button_Preview_Click(object sender, EventArgs e) { //对打印信息进行设置 PrintClass dgp = new PrintClass(this.dataGridView1, comboBox_PageSize.Text, checkBox_Aspect.Checked); MSetUp(dgp);//记录窗体中打印信息的相关设置 string[] header = new string[dataGridView1.ColumnCount];//创建一个与数据列相等的字符串数组 for (int p = 0; p < dataGridView1.ColumnCount; p++)//记录所有列标题的名列 { header[p] = dataGridView1.Columns[p].HeaderCell.Value.ToString(); } dgp.print();//显示打印预览窗体 } #region 设置打印数据的相关信息 /// <summary> /// 设置打印数据的相关信息 /// </summary> /// <param dgp="PrintClass">公共类PrintClass</param> private void MSetUp(PrintClass dgp) { dgp.PageAspect = Aspect;//设置横向打印 } #endregion
以上就是C#操作Word打印的示例的详细内容,更多关于C#操作Word打印的资料请关注猪先飞其它相关文章!
上一篇: C# 操作网络适配器的示例
下一篇: Unity实现刮奖效果
相关文章
- 下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
- 我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
- 这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
- 这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
Jupyter Notebook读取csv文件出现的问题及解决
这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06- 这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25- 这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
- 这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
- 本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
- 轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
- 这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
- 这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
- 这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25