1. 程式人生 > >以下是一個完整的關閉excel程序的例子

以下是一個完整的關閉excel程序的例子

,我剛用過,沒有問題了。
Excel.Application myExcel;
Excel._Workbook myWB;
Excel._Worksheet myWS = null;
Excel.Range myRrange = null;
try
{
    myExcel = new Excel.ApplicationClass();
    myWB = (Excel._Workbook)myExcel.Workbooks.Open(file.FullName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
}
catch(Exception e)
{
    e.ToString();
}
int SheetNum = myWB.Worksheets.Count;
if(SheetNum >0)
{
   for(int i=1;i<=SheetNum;i++)
   {
      myWS = (Excel._Worksheet)myWB.Worksheets[i];

 int RowNum = myWS.UsedRange.Cells.Rows.Count;
 if(RowNum >= 2)
 {
     for(int j=2;j<=RowNum;j++)
     {
  myRrange = myWS.get_Range("A"+j.ToString(), "E"+j.ToString());
  Array myvalues = (Array)myRrange.Cells.Value;
     }
 }
   }

//以下內容全都不能少!!
myWB.Close(false, Type.Missing, Type.Missing);
myExcel.Workbooks.Close();
myExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(myRrange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myWS);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myWB);
myWS = null;
myWB = null;
myExcel = null;
GC.Collect();