Skip to main content
黑话筒

C#简单操作Excel(一)

最近要给客户生成Excel报表,比较麻烦,以前生成是引用的SmartExcel来输出Excel文件,但是输出的文件由于格式较老,缺少很多功能,连单元格合并都不行。所以还是直接引用Excel.dll,来实现完整的Excel控制。

一、首先将Excel.exe复制到C:\里,在命令提示符窗口(cmd.exe)里输入path %path%;C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\bin。系统应该没有什么提示。然后输入c:回车,再输入cd\回车,如入tlbimp.exe excel.exe,之后系统会显示详细信息,如果没有出现错误,就会得到一个Excel.dll文件,这个文件就是经过转化的.net下的Excel。tlbimp的详细使用信息,请在命令提示符窗口里直接输入tlbimp。

二、然后打开Microsoft Visual Studio .NET 2003,新建一个C# WinForm工程,然后点击“项目” -“添加引用”,点击“浏览”,选择刚才生成的Excel.dll,再点“确定”。这样就引用了Excel.dll文件。 然后添加两个按钮,分别叫button1和button2,将button1的Text属性设为“简单”;将button2的Text属性设为“复杂”。双击button1,输入以下代码:

Excel.ApplicationClass myex=new Excel.ApplicationClass();    //创建Excel实例
myex.Visible=true;    //让Excel窗口可见

//添加一个新的工作表(WorkSheet),参数是模板类型
myex.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

myex.Cells[1,1]="hi";    //向单元格1,1填写数据

双击button2,添加下面的代码:

Excel.ApplicationClass myex=new Excel.ApplicationClass();    //创建Excel实例
myex.Visible=true;    //让Excel窗口可见

//添加一个新的工作表(WorkSheet),参数是模板类型
Excel._Workbook mywb=myex.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel._Worksheet myws=(Excel._Worksheet)mywb.Worksheets.get_Item(1);    //得到第一张工作表

Excel.Range rg=myws.get_Range("A1","E1");    //创建一个选取范围的实例

string []content=new string[6];    //创建数组
content[]="'1";
content[1]="'2";
content[2]="'3";
content[3]="'4";
content[4]="'5";
object []args1=new object[1];    //这是下面要引用到的参数数组,该数组仅包含一个元素
args1[]=content;    //设定参数数组第1个元素的内容为上面定义的内容数组

//调用...方法,将各个参数带入,最后两个参数分别为上面创建的“选取范围实例”和“参数数组”
rg.GetType().InvokeMember("Value",BindingFlags.SetProperty,null,rg,args1);

运行程序,分别点击“简单”和“复杂”,来看看这两者实现上的区别。

这样在每点击一次按钮后,系统中就多了一个Excel.exe的进程,当你关闭程序时,这些进程也不会自动消失。解决办法就是在使用完Excel的Application对象后,写入

myex.Quit();
myex=null;
GC.Collect();

来关闭Excel进程,并手工进行垃圾收集。如果不用这个方法,直接读取系统进程列表,杀死Excel.exe所对应的进程也可以,不过这样做有一定的危险性,所以最好还是采取上面的办法。

现在能通过C#打开Excel,并能通过两种方式向其中填入数据了。至于保存等操作,下次再说。

本次的完整代码:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
  /// 
  /// Form1 的摘要说明。
  /// 
  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    /// 
    /// 必需的设计器变量。
    /// 
    private System.ComponentModel.Container components = null;
    public Form1()
    {
      //
      // Windows 窗体设计器支持所必需的
      //
      InitializeComponent();
      //
      // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
      //
    }
    /// 
    /// 清理所有正在使用的资源。
    /// 
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    /// 
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// 
    private void InitializeComponent()
    {
      this.button1 = new System.Windows.Forms.Button();
      this.button2 = new System.Windows.Forms.Button();
      this.SuspendLayout();
      //
      // button1
      //
      this.button1.Location = new System.Drawing.Point(24, 32);
      this.button1.Name = "button1";
      this.button1.TabIndex = ;
      this.button1.Text = "简单";
      this.button1.Click += new System.EventHandler(this.button1_Click);
      //
      // button2
      //
      this.button2.Location = new System.Drawing.Point(160, 32);
      this.button2.Name = "button2";
      this.button2.TabIndex = 1;
      this.button2.Text = "复杂";
      this.button2.Click += new System.EventHandler(this.button2_Click);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Controls.Add(this.button2);
      this.Controls.Add(this.button1);
      this.Name = "Form1";
      this.Text = "Form1";
      this.ResumeLayout(false);
    }

    /// 
    /// 应用程序的主入口点。
    /// 
    [STAThread]
    static void Main()
    {
      Application.Run(new Form1());
    }
    private void button1_Click(object sender, System.EventArgs e)    //逐个单元格的填入数据
    {
      Excel.ApplicationClass myex=new Excel.ApplicationClass();    //创建Excel实例
      myex.Visible=true;    //让Excel窗口可见

      //添加一个新的工作表(WorkSheet),参数是模板类型
      myex.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

      myex.Cells[1,1]="hi";    //向单元格1,1填写数据
    }

    //将数组内容一次性填写到Excel
    private void button2_Click(object sender, System.EventArgs e)
    {
      Excel.ApplicationClass myex=new Excel.ApplicationClass();    //创建Excel实例
      myex.Visible=true;    //让Excel窗口可见

      //添加一个新的工作表(WorkSheet),参数是模板类型
      Excel._Workbook mywb=myex.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

      //得到第一张工作表
      Excel._Worksheet myws=(Excel._Worksheet)mywb.Worksheets.get_Item(1);

      Excel.Range rg=myws.get_Range("A1","E1");    //创建一个选取范围的实例

      string []content=new string[6];    //创建数组
      content[]="'1";
      content[1]="'2";
      content[2]="'3";
      content[3]="'4";
      content[4]="'5";

      //这是下面要引用到的参数数组,该数组仅包含一个元素
      object []args1=new object[1];

      //设定参数数组第1个元素的内容为上面定义的内容数组
      args1[]=content;

      //调用...方法,将各个参数带入
      //最后两个参数分别为上面创建的“选取范围实例”和“参数数组”
      rg.GetType().InvokeMember("Value",BindingFlags.SetProperty,null,rg,args1);
    }
  }
}