[转载]c#导出到excel

//导出Excel的方法
  private void ExportExcel()
  

   DataSet ds
=dtsSelect;//数据源
   if(ds==nullreturn

   
string saveFileName=""
   
bool fileSaved=false
   SaveFileDialog saveDialog
=new SaveFileDialog(); 
   saveDialog.DefaultExt 
="xls"
   saveDialog.Filter
="Excel文件|*.xls"
   saveDialog.FileName 
="Sheet1"
   saveDialog.ShowDialog(); 
   saveFileName
=saveDialog.FileName; 
   
if(saveFileName.IndexOf(":")<0return//被点了取消 

   Excel.Application xlApp
=new Excel.Application(); 

   
if(xlApp==null)
   

    MessageBox.Show(
"无法创建Excel对象,可能您的机子未安装Excel"); 
    
return
   }
 

   Excel.Workbooks workbooks
=xlApp.Workbooks; 
   Excel.Workbook workbook
=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); 
   Excel.Worksheet worksheet
=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
   
//写入字段 
   for(int i=0;i<ds.Tables[0].Columns.Count;i++)
   

    worksheet.Cells[
1,i+1]=ds.Tables[0].Columns[i].ColumnName; 
   }
 
   
//写入数值 
   
   
for(int r=0;r<ds.Tables[0].Rows.Count;r++)
   

    
for(int i=0;i<ds.Tables[0].Columns.Count;i++)
    

     worksheet.Cells[r
+2,i+1]=ds.Tables[0].Rows[r][i]; 
    }
 
    System.Windows.Forms.Application.DoEvents(); 
   }
 
   worksheet.Columns.EntireColumn.AutoFit();
//列宽自适应。
   if(cmbxType.Text!="Notification")
   
{
    Excel.Range rg
=worksheet.get_Range(worksheet.Cells[2,2],worksheet.Cells[ds.Tables[0].Rows.Count+1,2]);
    rg.NumberFormat
="00000000";
   }

   
if(saveFileName!="")
   

    
try
    

     workbook.Saved 
=true
     workbook.SaveCopyAs(saveFileName); 
     fileSaved
=true
    }

    
catch(Exception ex)
    

     fileSaved
=false
     MessageBox.Show(
"导出文件时出错,文件可能正被打开!\n"+ex.Message); 
    }
 
   }

   
else
   

    fileSaved
=false
   }
 
   xlApp.Quit(); 
   GC.Collect();
//强行销毁 
   if(fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
  }


posted @ 2007-10-25 17:10  水静痕迹  阅读(102)  评论(0编辑  收藏  举报