将中DataSet的数据导出为EXCEL文件

类别:网站制作 点击:0 评论:0 推荐:

/**//// <summary>
  /// 执行导出 ,请在项目中先引用Mircorsoft Excel library 11.0
  /// </summary>
  /// <param name="ds">要导出的DataSet</param>
  /// <param name="strExcelFileName">要导出的文件名</param>
  private void doExport(DataSet ds,string strExcelFileName)
  {
           
   Excel.Application excel= new Excel.Application();
           
   //            Excel.Workbook obj=new Excel.WorkbookClass();
   //            obj.SaveAs("c:\zn.xls",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null);

   int rowIndex=1;
   int colIndex=0;

   excel.Application.Workbooks.Add(true);
           
   
   System.Data.DataTable table=ds.Tables[0] ;
   foreach(DataColumn col in table.Columns)
   {
    colIndex++;   
    excel.Cells[1,colIndex]=col.ColumnName;               
   }

   foreach(DataRow row in table.Rows)
   {
    rowIndex++;
    colIndex=0;
    foreach(DataColumn col in table.Columns)
    {
     colIndex++;
     excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
    }
   }
   excel.Visible=false;   
   //excel.Sheets[0] = "sss";
   excel.ActiveWorkbook.SaveAs(strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
           
           
   //wkbNew.SaveAs strBookName


   //excel.Save(strExcelFileName);
   excel.Quit();
   excel=null;
           
   GC.Collect();//垃圾回收
  }
  #endregion

本文地址:http://com.8s8s.com/it/it30600.htm