日期:2010-05-01  浏览次数:20364 次

.NET封装了EXCEL相关的类,以下是实现在程序中标工具条中点击“EXCEL输出”按钮而触发的事件,前提是你的系统中装有EXCEL。
这是我的代码,有注释说明:
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
  {//工具条各个按纽单击事件
   if(e.Button==excelOut)
   {
    Excel.Application excelKccx = new Excel.Application();//创建excel对象
    excelKccx.Workbooks.Add(true);//创建excel工作薄
   
    DataTable myDataTable=myDataSet.Tables["库存信息"];//创建一个数据表,得到DataSet中“库存信息”表中的数据
    int row=2;
  
    //把数据表的各个信息输入到excel表中
    for(int i=0;i<myDataTable.Columns.Count;i++)//取字段名
    {
     excelKccx.Cells[1,i+1]=myDataTable.Columns[i].ColumnName.ToString();
    }
    for(int i=0;i<myDataTable.Rows.Count;i++ )//取记录值
    {

     for(int j=0;j<myDataTable.Columns.Count;j++)
     {     
      excelKccx.Cells[row,j+1]=myDataTable.Rows[i][j].ToString();
     }
     row++;
    }   
    excelKccx.Visible=true;//使excel可见*/
   }
   else if(e.Button==reportForm)
   {
    //kcRptForm myReport=new kcRptForm();
    //myReport.MdiParent=this;
    //myReport.Show();
   }

出处:随心所动 BLOG