C#操作MS Word 和 MS Excel

閑話少敘﹐直接講步驟﹕

1﹑首先﹐需要引用以下兩個COM﹐Microsoft Excel 9.0 Object Library和Microsoft Word 9.0 Object Library(我所使用的是Office200,XP好象是10.0的)

2﹑拷貝如下代碼即可﹕

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace WindowsApplication1
{
 /// <summary>
 /// Form1 的摘要描述。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button1;
  /// <summary>
  /// 設計工具所需的變數。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows Form 設計工具支援的必要項
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 呼叫之後加入任何建構函式程式碼
   //
  }

  /// <summary>
  /// 清除任何使用中的資源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form 設計工具產生的程式碼
  /// <summary>
  /// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改
  /// 這個方法的內容。
  /// </summary>
  private void InitializeComponent()
  {
            this.button2 = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // button2
            //
            this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button2.Location = new System.Drawing.Point(32, 56);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(96, 23);
            this.button2.TabIndex = 3;
            this.button2.Text = "Open Word";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // button1
            //
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button1.Location = new System.Drawing.Point(32, 16);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(96, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "Open Excel";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(160, 102);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }
  #endregion

  /// <summary>
  /// 應用程式的主進入點。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }
        private DataTable CreateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("姓名",typeof(string));
            dt.Columns.Add("年齡",typeof(int));
            dt.Columns.Add("性別",typeof(string));
            dt.Columns.Add("地址",typeof(string));
            DataRow dr = dt.NewRow();
            dr.BeginEdit();
            dr["姓名"] = "張三";
            dr["年齡"] = "24";
            dr["性別"] = "男";
            dr["地址"] = "廣東深圳";
            dr.EndEdit();
            dt.Rows.Add(dr);
            return dt;
        }
        private void CreateExcel()
        {
            Excel.Application xlApp = new Excel.ApplicationClass();
            Excel.Workbook  xlBook;
            Excel.Worksheet xlSheet ;
            DataTable dt;
            int rowIndex,colIndex;
            xlBook = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            xlSheet= (Excel.Worksheet)xlBook.Worksheets["Sheet1"];
            dt = CreateTable();         
            rowIndex = 1;
            colIndex = 0;
            foreach(DataColumn Col in dt.Columns)
            {
                colIndex++;
                xlApp.Cells[1,colIndex] = Col.ColumnName;
            }
            foreach(DataRow Row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach(DataColumn Col in dt.Columns)
                {
                    colIndex++;
                    xlApp.Cells[rowIndex,colIndex] = Row[Col.ColumnName];
                }
            }

            xlSheet.get_Range(xlSheet.Cells[1,1],xlSheet.Cells[1,colIndex]).Font .Name = "黑體";
            xlSheet.get_Range(xlSheet.Cells[1,1],xlSheet.Cells[1,colIndex]).Font .Bold  = true;
            xlSheet.get_Range(xlSheet.Cells[1,1],xlSheet.Cells[rowIndex,colIndex]).Borders.LineStyle  = 1;

            xlSheet.PageSetup.LeftHeader   = "公司名稱﹕";
            xlSheet.PageSetup.CenterHeader = "公司人員情況表﹕";
            xlSheet.PageSetup.RightHeader  = "單位﹕";
            xlSheet.PageSetup.LeftFooter   = "制表人﹕";
            xlSheet.PageSetup.CenterFooter = "制表日期﹕";
            xlSheet.PageSetup.RightFooter  = "第&P頁 共&N頁";
            xlApp.Visible = true;

        }

        private void CreateWord()
        {
            Word.Application wdApp= new Word.ApplicationClass();
            Word.Document wdDoc;
            Word.Table wdTab;
            DataTable dt;
            int rowIndex,colIndex;
            object oVisible = true;
            object oMissing = System.Reflection.Missing.Value;
            object oStart = 0;
            object oEnd = 0;
            wdDoc = wdApp.Documents.Add(ref oMissing,ref oMissing,ref oMissing,ref oVisible);
            rowIndex = 1;
            colIndex = 0;
            dt  = CreateTable();
            wdTab = wdDoc.Tables.Add(wdDoc.Range(ref oStart,ref oEnd),dt.Rows.Count +1,dt.Columns.Count,ref oMissing,ref oMissing);
            foreach(DataColumn Col in dt.Columns)
            {
                colIndex++;
                wdTab.Cell(1,colIndex).Range.InsertAfter(Col.ColumnName);
            }
            foreach(DataRow Row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach(DataColumn Col in dt.Columns)
                {
                    colIndex++;
                    wdTab.Cell(rowIndex,colIndex).Range.InsertAfter(Row[Col.ColumnName].ToString());
                }
            }
            wdTab.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;
            wdTab.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            wdApp.Visible = true;
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            CreateExcel();
            GC.Collect();
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            CreateWord();
        }

 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值