C#操作Word打印的示例
话不多说,解释在代码注释中……
classPrintClass
{
#region全局变量
privateDataGridViewdatagrid;//需要打印的数据来源
privatePageSetupDialogpagesetupdialog;
privatePrintPreviewDialogprintpreviewdialog;
intcurrentpageindex=0;//当前页的编号
introwcount=0;//数据的行数
publicSizePaperSize=newSize(827,1169);//答应的纸张大小
publicintheaderheight=30;//标题高度
Marginsmargins=newMargins(50,60,50,80);
publicintcelltopmargin=6;//单元格顶边距
publicintpagerowcount=7;//每页行数
publicintrowgap=23;//行高
publicintcolgap=5;//每列间隔
publicFontheaderfont=newFont("Arial",9,FontStyle.Bold);//列名标题字体
publicBrushbrushHeaderFont=newSolidBrush(Color.Black);//列名字体画刷
publicFontCellfont=newFont("Arial",9);//单元格字体
publicboolisautopagerowcount=true;//是否自动计算行数
publicboolPageAspect=false;//打印的方向
publicstaticboolPageScape=false;//打印方向
publicstringpaperName=string.Empty;
#endregion
#region打印信息的初始化
///
///打印信息的初始化
///
///打印数据
///纸张大小
///是否横向打印
publicPrintClass(DataGridViewdatagrid,stringpaperName,boollendscape)
{
this.datagrid=datagrid;//获取打印数据
this.paperName=paperName;
PrintDocumentprintdocument=newPrintDocument();//实例化PrintDocument类
printpreviewdialog=newPrintPreviewDialog();//实例化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=newPageSetupDialog();//实例化PageSetupDialog类
pagesetupdialog.Document=printdocument;//获取当前页的设置
printdocument.PrintPage+=newPrintPageEventHandler(this.printdocument_printpage);//事件的重载
}
#endregion
#region页的打印事件
///
///页的打印事件(主要用于绘制打印报表)
///
privatevoidprintdocument_printpage(objectsender,System.Drawing.Printing.PrintPageEventArgse)
{
if(this.isautopagerowcount)//自动计算页的行数
{
doublecountHeight=e.PageBounds.Height-this.margins.Top-this.headerfont.Height-this.headerheight-this.margins.Bottom;
pagerowcount=(int)Math.Ceiling(countHeight/this.rowgap);//获取每页的行数
}
intpagecount=(int)(rowcount/pagerowcount);//获取打印多少页
pagesetupdialog.AllowOrientation=true;//启动打印页面对话框的方向部分
intcolcount=0;//记录数据的列数
inty=margins.Top;//获取表格的顶边距
stringcellvalue="";//记录文本信息(单元格的文本信息)
intstartrow=currentpageindex*pagerowcount;//设置打印的初始页数
intendrow=startrow+this.pagerowcount0)//如果列的宽大于0
{
cwidth+=datagrid.Columns[j].Width+colgap;//累加每列的宽度
}
}
y+=rowgap;//设置表格的上边线的位置
//设置标题栏中的文字
for(intj=0;j0)//如果列的宽度大于0
{
cellvalue=datagrid.Columns[j].HeaderText;//获取列标题
//绘制标题栏文字
e.Graphics.DrawString(cellvalue,headerfont,brushHeaderFont,x,y+celltopmargin);//绘制列标题
x+=colwidth+colgap;//横向,下一个单元格的位置
intnnp=y+currentpagerowcount*rowgap+this.headerheight;//下一行线的位置
}
}
//打印所有的行信息
for(inti=startrow;i0)//如果列的宽度大于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(newchar[]{'\r','\n'}).Length-1);//单元格信息的Y坐标
}
}
y+=rowgap;//设置下行的位置
}
currentpageindex++;//下一页的页码
if(currentpageindex
///显示打印预览窗体
///
publicvoidprint()
{
rowcount=0;//记录数据的行数
PageSettingsstorePageSetting=newPageSettings();//实列化一个对PageSettings对象
PrintDocumentprintdocument=pagesetupdialog.Document;
foreach(PaperSizepsinprintdocument.PrinterSettings.PaperSizes)//查找当前设置纸张
{
if(paperName==ps.PaperName)//如果找到当前纸张的名称
{
printdocument.DefaultPageSettings.PaperSize=ps;//获取当前纸张的信息
}
}
if(datagrid.DataSourceisSystem.Data.DataTable)//判断数据类型
{
rowcount=((DataTable)datagrid.DataSource).Rows.Count;//获取数据的行数
}
elseif(datagrid.DataSourceisSystem.Collections.ArrayList)//判断数据类型
{
rowcount=((ArrayList)datagrid.DataSource).Count;//获取数据的行数
}
try
{
printdocument.DefaultPageSettings.Landscape=PageScape;//设置横向打印
printpreviewdialog.ShowDialog();//显示打印预览窗体
}
catch(Exceptione)
{
thrownewException("printererror."+e.Message);
}
}
#endregion
}
创建一个打印窗体
设计页面代码:
//////设计器支持所需的方法-不要 ///使用代码编辑器修改此方法的内容。 /// privatevoidInitializeComponent() { this.dataGridView1=newSystem.Windows.Forms.DataGridView(); this.groupBox1=newSystem.Windows.Forms.GroupBox(); this.label8=newSystem.Windows.Forms.Label(); this.comboBox_PageSize=newSystem.Windows.Forms.ComboBox(); this.button_Preview=newSystem.Windows.Forms.Button(); this.checkBox_Aspect=newSystem.Windows.Forms.CheckBox(); this.panel_Line=newSystem.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=newSystem.Drawing.Point(3,4); this.dataGridView1.Name="dataGridView1"; this.dataGridView1.RowTemplate.Height=23; this.dataGridView1.Size=newSystem.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=newSystem.Drawing.Point(1088,4); this.groupBox1.Name="groupBox1"; this.groupBox1.Size=newSystem.Drawing.Size(144,287); this.groupBox1.TabIndex=1; this.groupBox1.TabStop=false; this.groupBox1.Text="打印设置"; // //label8 // this.label8.AutoSize=true; this.label8.Location=newSystem.Drawing.Point(2,232); this.label8.Name="label8"; this.label8.Size=newSystem.Drawing.Size(65,12); this.label8.TabIndex=19; this.label8.Text="纸张大小:"; // //comboBox_PageSize // this.comboBox_PageSize.FormattingEnabled=true; this.comboBox_PageSize.Items.AddRange(newobject[]{ "A4", "A5", "A6", "B5(JIS)", "B5", "16K"}); this.comboBox_PageSize.Location=newSystem.Drawing.Point(67,229); this.comboBox_PageSize.Name="comboBox_PageSize"; this.comboBox_PageSize.Size=newSystem.Drawing.Size(71,20); this.comboBox_PageSize.TabIndex=18; // //button_Preview // this.button_Preview.Location=newSystem.Drawing.Point(34,254); this.button_Preview.Name="button_Preview"; this.button_Preview.Size=newSystem.Drawing.Size(70,23); this.button_Preview.TabIndex=17; this.button_Preview.Text="打印预览"; this.button_Preview.UseVisualStyleBackColor=true; this.button_Preview.Click+=newSystem.EventHandler(this.button_Preview_Click); // //checkBox_Aspect // this.checkBox_Aspect.AutoSize=true; this.checkBox_Aspect.Location=newSystem.Drawing.Point(34,211); this.checkBox_Aspect.Name="checkBox_Aspect"; this.checkBox_Aspect.Size=newSystem.Drawing.Size(72,16); this.checkBox_Aspect.TabIndex=15; this.checkBox_Aspect.Text="横向打印"; this.checkBox_Aspect.UseVisualStyleBackColor=true; this.checkBox_Aspect.MouseDown+=newSystem.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=newSystem.Drawing.Point(23,74); this.panel_Line.Name="panel_Line"; this.panel_Line.Size=newSystem.Drawing.Size(100,116); this.panel_Line.TabIndex=6; // //Form1 // this.AutoScaleDimensions=newSystem.Drawing.SizeF(6F,12F); this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font; this.ClientSize=newSystem.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+=newSystem.EventHandler(this.Form1_Activated); this.Load+=newSystem.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); }
操作代码:
publicboolAspect=true;//打印方向
publicboolboundary=false;//是否打印分割线
privatevoidForm1_Activated(objectsender,EventArgse)
{
//在窗体中绘制一个预览表格
Graphicsg=panel_Line.CreateGraphics();
intpaneW=panel_Line.Width;//设置表格的宽度
intpaneH=panel_Line.Height;//设置表格的高度
g.DrawRectangle(newPen(Color.WhiteSmoke,paneW),0,0,paneW,paneH);//绘制一个矩形
}
privatevoidForm1_Load(objectsender,EventArgse)
{
comboBox_PageSize.SelectedIndex=0;
OleDbConnectionoledbCon=newOleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\\Users\\Lenovo\\Desktop\\SnapShot.mdb;");
OleDbDataAdapteroledbDa=newOleDbDataAdapter("select*fromRegionInfo",oledbCon);
DataSetmyds=newDataSet();
oledbDa.Fill(myds);
dataGridView1.DataSource=myds.Tables[0];
}
privatevoidcheckBox_Aspect_MouseDown(objectsender,MouseEventArgse)
{
//改变窗体中预览表格的方向
intaspX=0;//宽度
intaspY=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=newPoint(aspX,90);//设置控件的位置
Form1_Activated(sender,e);//设用Activated事件
}
privatevoidbutton_Preview_Click(objectsender,EventArgse)
{
//对打印信息进行设置
PrintClassdgp=newPrintClass(this.dataGridView1,comboBox_PageSize.Text,checkBox_Aspect.Checked);
MSetUp(dgp);//记录窗体中打印信息的相关设置
string[]header=newstring[dataGridView1.ColumnCount];//创建一个与数据列相等的字符串数组
for(intp=0;p
///设置打印数据的相关信息
///
///公共类PrintClass
privatevoidMSetUp(PrintClassdgp)
{
dgp.PageAspect=Aspect;//设置横向打印
}
#endregion
以上就是C#操作Word打印的示例的详细内容,更多关于C#操作Word打印的资料请关注毛票票其它相关文章!