服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#操作Word打印的示例

C#操作Word打印的示例

2022-10-12 13:48一只独行的猿 C#

这篇文章主要介绍了C#操作Word打印的示例,帮助大家利用c#打印文件,提高办公效率,感兴趣的朋友可以了解下

话不多说,解释在代码注释中……

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
}

创建一个打印窗体

设计页面代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/// <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);
 
}

操作代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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打印的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/pilgrim/p/13502073.html

延伸 · 阅读

精彩推荐
  • C#C# 中的var关键字详细介绍

    C# 中的var关键字详细介绍

    这篇文章主要介绍了C# 中的var关键字详细介绍的相关资料,需要的朋友可以参考下...

    C#教程网11252021-12-14
  • C#详解C#编程中一维数组与多维数组的使用

    详解C#编程中一维数组与多维数组的使用

    这篇文章主要介绍了详解C#编程中一维数组与多维数组的使用,包括数组初始化等基础知识的讲解,需要的朋友可以参考下...

    C#教程网5562021-11-09
  • C#C#语法之泛型的多种应用

    C#语法之泛型的多种应用

    这篇文章主要介绍了C#语法之泛型的多种应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着...

    Kiba51811332022-07-29
  • C#浅析C# Dynamic关键字

    浅析C# Dynamic关键字

    这篇文章主要介绍了C# Dynamic关键字的相关资料,文中讲解非常细致,对大家学习C# Dynamic关键字有所帮助,感兴趣的朋友可以了解下...

    每天进步多一点9512022-09-29
  • C#C#实现Access通用访问类OleDbHelper完整实例

    C#实现Access通用访问类OleDbHelper完整实例

    这篇文章主要介绍了C#实现Access通用访问类OleDbHelper,结合完整实例形式分析了C#针对access数据库的连接、查询、遍历、分页显示等相关操作技巧,需要的朋友...

    蓝之风7922021-12-27
  • C#C# 开发step步骤条控件详解

    C# 开发step步骤条控件详解

    本篇文章主要介绍了用C#来实现一个step控件的方法步骤,具有很好的参考价值。下面跟着小编一起来看下吧...

    JackWang-CUMT7772021-12-28
  • C#C# 设计模式系列教程-命令模式

    C# 设计模式系列教程-命令模式

    在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变...

    Wang Juqiang5412021-11-23
  • C#vs代码段快捷键设置(图文)

    vs代码段快捷键设置(图文)

    学习代码快捷键是程序员必学知识点,会使用代码快捷在程序开发过程中会提高开发效率,下面小编给大家整理些有关vs代码段快捷键设置的技巧,需要的...

    碎儿7812021-10-19