1. 程式人生 > 實用技巧 >C#操作Word列印

C#操作Word列印

話不多說,解釋在程式碼註釋中……

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);

}
View Code

操作程式碼:

 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