操作EXCEL文件成功释放COM对象的代码

来源:互联网 发布:怎样申请手机淘宝帐号 编辑:程序博客网 时间:2024/06/08 04:06

    Excel.Application app = new Excel.ApplicationClass();
    Excel.Workbooks  workbooks = app.Workbooks;
    Excel._Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
    Excel.Sheets sheets = workbook.Sheets;
    Excel._Worksheet worksheet = (Excel._Worksheet)sheets.get_Item(1);
    Excel.Range  range = worksheet.Cells;
   for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
   {
    range[1,i] = ds.Tables[0].Columns[i-1].ColumnName;
   }

   for(int n = 0 ; n < ds.Tables[0].Rows.Count; n++)
   {
    for(int m = 1; m <= ds.Tables[0].Columns.Count; m++)
    {
     range[n+2,m] = ds.Tables[0].Rows[n][m-1].ToString();
    }
   }
    
   if(System.IO.File.Exists("d://excel.xls"))
   {
    System.IO.File.Delete("d://excel.xls");
   }
    worksheet.SaveAs("d://excel.xls",Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
    //app.Visible = true;
    
    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    range = null;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
   worksheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
   sheets = null;
   workbook.Close(false,Missing.Value,Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
   workbook = null;
   workbooks.Close();
   System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
   workbooks = null;
   app.Quit();
   System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
   app = null;