从Excel导入到DataSet

///   <summary>   
  
///   将数据集导入指定的EXCEL文件   
  
///   </summary>   
  
///   <param   name="dt"></param>   
  
///   <returns></returns>   
  public   static   bool   ToExcel(DataTable   dt)   
  {   
    
  
try   
  {   
  Excel.Application   excel
=   new   Excel.ApplicationClass();   
  
int   rowIndex=1;   
  
int   colIndex=0;   
    
  
//excel.Workbooks.   
  excel.Application.Workbooks.Add(true);   
    
  
//将所得到的表的列名,赋值给单元格   
  foreach(DataColumn   col   in   dt.Columns)   
  {   
  colIndex
++;     
  excel.Cells[
1,colIndex]=col.ColumnName;     
  }   
    
  
//同样方法处理数据   
  foreach(DataRow   row   in   dt.Rows)   
  {   
  rowIndex
++;   
  colIndex
=0;   
  
foreach(DataColumn   col   in   dt.Columns)   
  {   
  colIndex
++;   
  excel.Cells[rowIndex,colIndex]
=row[col.ColumnName].ToString();   
  }   
  }   
  
//不可见,即后台处理   
  excel.Visible=true;     
    
  
// excel.Application.DisplayAlerts   =   false;   
  
// excel.Application.Quit();   
  
// foreach(System.Diagnostics.Process   p   in   System.Diagnostics.Process.GetProcesses())     
  
// {   
  
// if(p.ProcessName.ToUpper()   ==   "EXCEL")   
  
// {   
  
// p.Kill();   
  
// }   
  
// }   
    
  
return   true;   
  }   
  
catch(Exception   err)   
  {   
  
return   false;   
  }   
    
    
    
  }
posted @ 2007-11-20 11:50  谢杰  阅读(547)  评论(0编辑  收藏  举报