搜索吧

首页 » 搜成宝库 » 常用知识 » 将从数据库取出的内容写入一个新建的excel文件
xiaoyaoyou - 2009-12-8 14:37:26
下列方法描述如何将从数据库取出的内容(假设以dataset方式)写入一个excel文件 
  其中的this.getData()方法是获取datatable,代码已略去。 
  注:在开发之前需添加对office目录下EXCEL9.OLB的引用 
   
  private  void  button1_Click(object  sender,  System.EventArgs  e) 
  { 
   
  object  objMissing=System.Reflection.Missing.Value; 
  Excel.ApplicationClass  oExcel=new  Excel.ApplicationClass(); 
  Workbook  oBook=oExcel.Workbooks.Add(true); 
   
  System.Data.DataTable  dt=this.GetData(); 
   
   
  for(int  i=1;i<=dt.Columns.Count;i++) 
  { 
  oExcel.Cells[1,i]=dt.Columns[i-1].ColumnName; 
  } 
  for(int  i=1;i<=dt.Rows.Count;i++) 
  { 
  for(int  j=1;j<=dt.Columns.Count;j++) 
  { 
  oExcel.Cells[i+1,j]=dt.Rows[i-1][j-1].ToString(); 
  } 
   
  } 
   
  oExcel.Save("c:\\cs.xls"); 
   
  //oExcel.Visible=true; 
  oExcel.Quit(); 
  oExcel=null; 
   
  }
1
查看完整版本: 将从数据库取出的内容写入一个新建的excel文件