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

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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;

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航