C#操作Word打印的示例
更新時(shí)間:2020年10月28日 11:29:49 作者:一只獨(dú)行的猿
這篇文章主要介紹了C#操作Word打印的示例,幫助大家利用c#打印文件,提高辦公效率,感興趣的朋友可以了解下
話不多說,解釋在代碼注釋中……
class PrintClass { #region 全局變量 private DataGridView datagrid;//需要打印的數(shù)據(jù)來源 private PageSetupDialog pagesetupdialog; private PrintPreviewDialog printpreviewdialog; int currentpageindex = 0;//當(dāng)前頁的編號(hào) int rowcount = 0;//數(shù)據(jù)的行數(shù) public Size PaperSize = new Size(827, 1169);//答應(yīng)的紙張大小 public int headerheight = 30;//標(biāo)題高度 Margins margins = new Margins(50, 60, 50, 80); public int celltopmargin = 6;//單元格頂邊距 public int pagerowcount = 7;//每頁行數(shù) public int rowgap = 23;//行高 public int colgap = 5;//每列間隔 public Font headerfont = new Font("Arial", 9, FontStyle.Bold);//列名標(biāo)題字體 public Brush brushHeaderFont = new SolidBrush(Color.Black);//列名字體畫刷 public Font Cellfont = new Font("Arial", 9);//單元格字體 public bool isautopagerowcount = true;//是否自動(dòng)計(jì)算行數(shù) public bool PageAspect = false;//打印的方向 public static bool PageScape = false;//打印方向 public string paperName = string.Empty; #endregion #region 打印信息的初始化 /// <summary> /// 打印信息的初始化 /// </summary> /// <param datagrid="DataGridView">打印數(shù)據(jù)</param> /// <param PageS="int">紙張大小</param> /// <param lendscape="bool">是否橫向打印</param> public PrintClass(DataGridView datagrid, string paperName, bool lendscape) { this.datagrid = datagrid;//獲取打印數(shù)據(jù) this.paperName = paperName; PrintDocument printdocument = new PrintDocument();//實(shí)例化PrintDocument類 printpreviewdialog = new PrintPreviewDialog();//實(shí)例化PrintPreviewDialog類 printpreviewdialog.Document = printdocument;//獲取預(yù)覽文檔的信息 printpreviewdialog.FormBorderStyle = FormBorderStyle.Fixed3D;//設(shè)置窗體的邊框樣式 //橫向打印的設(shè)置 if (!string.IsNullOrEmpty(paperName) ) { if (lendscape == true) { printdocument.DefaultPageSettings.Landscape = lendscape;//橫向打印 } else { printdocument.DefaultPageSettings.Landscape = lendscape;//縱向打印 } } pagesetupdialog = new PageSetupDialog();//實(shí)例化PageSetupDialog類 pagesetupdialog.Document = printdocument;//獲取當(dāng)前頁的設(shè)置 printdocument.PrintPage += new PrintPageEventHandler(this.printdocument_printpage);//事件的重載 } #endregion #region 頁的打印事件 /// <summary> /// 頁的打印事件(主要用于繪制打印報(bào)表) /// </summary> private void printdocument_printpage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { if (this.isautopagerowcount)//自動(dòng)計(jì)算頁的行數(shù) { double countHeight = e.PageBounds.Height - this.margins.Top - this.headerfont.Height - this.headerheight - this.margins.Bottom; pagerowcount = (int)Math.Ceiling(countHeight / this.rowgap);//獲取每頁的行數(shù) } int pagecount = (int)(rowcount / pagerowcount);//獲取打印多少頁 pagesetupdialog.AllowOrientation = true;//啟動(dòng)打印頁面對(duì)話框的方向部分 int colcount = 0;//記錄數(shù)據(jù)的列數(shù) int y = margins.Top;//獲取表格的頂邊距 string cellvalue = "";//記錄文本信息(單元格的文本信息) int startrow = currentpageindex * pagerowcount;//設(shè)置打印的初始頁數(shù) int endrow = startrow + this.pagerowcount < rowcount ? startrow + pagerowcount : rowcount;//設(shè)置打印的最大頁數(shù) int currentpagerowcount = endrow - startrow;//獲取打印頁數(shù) colcount = datagrid.ColumnCount;//獲取打印數(shù)據(jù)的列數(shù) int x = margins.Left;//獲取表格的左邊距 繪畫時(shí)的x軸位置 //獲取報(bào)表的寬度 int cwidth = 0; for (int j = 0; j < colcount; j++)//循環(huán)數(shù)據(jù)的列數(shù) { if (datagrid.Columns[j].Width > 0)//如果列的寬大于0 { cwidth += datagrid.Columns[j].Width + colgap;//累加每列的寬度 } } y += rowgap;//設(shè)置表格的上邊線的位置 //設(shè)置標(biāo)題欄中的文字 for (int j = 0; j < colcount; j++)//遍歷列數(shù)據(jù) { int colwidth = datagrid.Columns[j].Width;//獲取列的寬度 if (colwidth > 0)//如果列的寬度大于0 { cellvalue = datagrid.Columns[j].HeaderText;//獲取列標(biāo)題 //繪制標(biāo)題欄文字 e.Graphics.DrawString(cellvalue, headerfont, brushHeaderFont, x, y + celltopmargin);//繪制列標(biāo)題 x += colwidth + colgap;//橫向,下一個(gè)單元格的位置 int nnp = y + currentpagerowcount * rowgap + this.headerheight;//下一行線的位置 } } //打印所有的行信息 for (int i = startrow; i < endrow; i++) //對(duì)行進(jìn)行循環(huán) { x = margins.Left; //獲取線的X坐標(biāo)點(diǎn) for (int j = 0; j < colcount; j++)//對(duì)列進(jìn)行循環(huán) { 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坐標(biāo) y = y + rowgap * (cellvalue.Split(new char[] { '\r', '\n' }).Length - 1);//單元格信息的Y坐標(biāo) } } y += rowgap;//設(shè)置下行的位置 } currentpageindex++;//下一頁的頁碼 if (currentpageindex < pagecount)//如果當(dāng)前頁不是最后一頁 { e.HasMorePages = true;//打印副頁 } else { e.HasMorePages = false;//不打印副頁 this.currentpageindex = 0;//當(dāng)前打印的頁編號(hào)設(shè)為0 } } #endregion #region 顯示打印預(yù)覽窗體 /// <summary> /// 顯示打印預(yù)覽窗體 /// </summary> public void print() { rowcount = 0;//記錄數(shù)據(jù)的行數(shù) PageSettings storePageSetting = new PageSettings();//實(shí)列化一個(gè)對(duì)PageSettings對(duì)象 PrintDocument printdocument = pagesetupdialog.Document; foreach (PaperSize ps in printdocument.PrinterSettings.PaperSizes)//查找當(dāng)前設(shè)置紙張 { if (paperName == ps.PaperName)//如果找到當(dāng)前紙張的名稱 { printdocument.DefaultPageSettings.PaperSize = ps;//獲取當(dāng)前紙張的信息 } } if (datagrid.DataSource is System.Data.DataTable)//判斷數(shù)據(jù)類型 { rowcount = ((DataTable)datagrid.DataSource).Rows.Count;//獲取數(shù)據(jù)的行數(shù) } else if (datagrid.DataSource is System.Collections.ArrayList)//判斷數(shù)據(jù)類型 { rowcount = ((ArrayList)datagrid.DataSource).Count;//獲取數(shù)據(jù)的行數(shù) } try { printdocument.DefaultPageSettings.Landscape = PageScape;//設(shè)置橫向打印 printpreviewdialog.ShowDialog();//顯示打印預(yù)覽窗體 } catch (Exception e) { throw new Exception("printer error." + e.Message); } } #endregion }
創(chuàng)建一個(gè)打印窗體
設(shè)計(jì)頁面代碼:
/// <summary> /// 設(shè)計(jì)器支持所需的方法 - 不要 /// 使用代碼編輯器修改此方法的內(nèi)容。 /// </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 = "打印設(shè)置"; // // 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 = "打印預(yù)覽"; 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) { //在窗體中繪制一個(gè)預(yù)覽表格 Graphics g = panel_Line.CreateGraphics(); int paneW = panel_Line.Width;//設(shè)置表格的寬度 int paneH = panel_Line.Height;//設(shè)置表格的高度 g.DrawRectangle(new Pen(Color.WhiteSmoke, paneW), 0, 0, paneW, paneH);//繪制一個(gè)矩形 } 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) { //改變窗體中預(yù)覽表格的方向 int aspX = 0;//寬度 int aspY = 0;//高度 if (((CheckBox)sender).Checked == false)//如果不是縱向打印 { aspX = 136;//設(shè)置大小 aspY = 98; PrintClass.PageScape = true;//橫向打印 } else { aspX = 100;//設(shè)置大小 aspY = 116; PrintClass.PageScape = false;//縱向打印 } panel_Line.Width = aspX;//設(shè)置控件的寬度 panel_Line.Height = aspY;//設(shè)置控件的高度 aspX = (int)((groupBox1.Width - aspX) / 2);//設(shè)置控件的Top panel_Line.Location = new Point(aspX, 90);//設(shè)置控件的位置 Form1_Activated(sender, e);//設(shè)用Activated事件 } private void button_Preview_Click(object sender, EventArgs e) { //對(duì)打印信息進(jìn)行設(shè)置 PrintClass dgp = new PrintClass(this.dataGridView1, comboBox_PageSize.Text, checkBox_Aspect.Checked); MSetUp(dgp);//記錄窗體中打印信息的相關(guān)設(shè)置 string[] header = new string[dataGridView1.ColumnCount];//創(chuàng)建一個(gè)與數(shù)據(jù)列相等的字符串?dāng)?shù)組 for (int p = 0; p < dataGridView1.ColumnCount; p++)//記錄所有列標(biāo)題的名列 { header[p] = dataGridView1.Columns[p].HeaderCell.Value.ToString(); } dgp.print();//顯示打印預(yù)覽窗體 } #region 設(shè)置打印數(shù)據(jù)的相關(guān)信息 /// <summary> /// 設(shè)置打印數(shù)據(jù)的相關(guān)信息 /// </summary> /// <param dgp="PrintClass">公共類PrintClass</param> private void MSetUp(PrintClass dgp) { dgp.PageAspect = Aspect;//設(shè)置橫向打印 } #endregion
以上就是C#操作Word打印的示例的詳細(xì)內(nèi)容,更多關(guān)于C#操作Word打印的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#使用XmlDocument或XDocument創(chuàng)建xml文件
這篇文章主要為大家詳細(xì)介紹了C#使用XmlDocument或XDocument創(chuàng)建xml文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10Unity Shader實(shí)現(xiàn)素描風(fēng)格的渲染
這篇文章主要為大家詳細(xì)介紹了Unity Shader實(shí)現(xiàn)素描風(fēng)格的渲染,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04C#利用Refit實(shí)現(xiàn)JWT自動(dòng)續(xù)期詳解
Refit?是一個(gè)受到Square的Retrofit庫(Java)啟發(fā)的自動(dòng)類型安全REST庫,這篇文章主要為大家介紹了C#如何利用Refit實(shí)現(xiàn)JWT自動(dòng)續(xù)期,感興趣的可以了解下2023-08-08C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口
這篇文章主要介紹了C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口,直接給出示例代碼,需要的朋友可以參考下2015-06-06C#巧用DateTime預(yù)設(shè)可選的日期范圍(如本年度、本季度、本月等)
這篇文章主要介紹了C#巧用DateTime預(yù)設(shè)可選的日期范圍,如本年度、本季度、本月等,感興趣的小伙伴們可以參考一下2016-04-04