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

    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;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值