2010-07-01 57 views
4

有沒有比Kill()更好的方法來存檔相同的結果。當我殺死()一個Excel進程時,下次打開任何Excel工作表時,將打開「文檔恢復」側欄,這是我不想做的。比Process.Kill更好的選擇()

+0

你必須讓Excel正常退出,並等待它退出,否則Excel將始終顯示文件恢復窗口。 – GenericTypeTea 2010-07-01 10:53:02

+0

您的代碼是否首先啓動Excel?如果是這樣,那麼一旦完成,這可能會提供關閉Excel的好方法。 – 2010-07-01 11:07:02

+0

它在Web瀏覽器組件中打開,並且不允許用戶手動更新工作表。 – Rabin 2010-07-01 11:20:40

回答

2

不確定這是否有助於Excel在Web瀏覽器中運行。如果你能搶的運行,你可以找到你想要關閉該工作簿的Excel實例...

try 
{ 
    // Grab a reference to an open instance of Excel 
    var oExcelApp = 
     (Microsoft.Office.Interop.Excel.Application) 
     Marshal.GetActiveObject("Excel.Application"); 

    // Loop around the workbooks to find the one you want to close 
    for (int i = 1; i <= oExcelApp.Workbooks.Count; i++) 
    { 
     if (oExcelApp.Workbooks[i].Name == "requiredname") 
      oExcelApp.Workbooks[i].Close(Type.Missing, Type.Missing, Type.Missing); 

    } 

    // Clear up... 
    Marshal.FinalReleaseComObject(oExcelApp); 

} 
catch(Exception ex) 
{ 
    // Something went wrong... 
} 
+0

謝謝安迪隊友。 – Rabin 2010-07-02 09:46:45

5

添加.Net參考Microsoft.Office.Interop.Excel。那麼不妨看看下面的代碼我拼湊:

Microsoft.Office.Interop.Excel.ApplicationClass _excel; 
Microsoft.Office.Interop.Excel.Workbook _workBook; 

private void Form1_Load(object sender, EventArgs e) 
{ 
    _excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    _excel.Visible = true; 

    // Open the workbook 
    _workBook = _excel.Workbooks.Open(@"DataSheet.xls", 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing); 

} 

private void btn_Close_Click(object sender, EventArgs e) 
{ 

    GC.Collect(); 
    GC.WaitForPendingFinalizers(); 

    _workBook.Close(false, Type.Missing, Type.Missing); 
    _excel.Quit(); 

    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_workBook); 
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_excel); 

} 
+0

我試過這個,但是下次我打開同一個文件時,它會給出錯誤。 – Rabin 2010-07-01 10:51:55

+0

@Rabin - 提供一個代碼示例。 – GenericTypeTea 2010-07-01 10:52:27

+0

Btw,'Process.Close'是'Process.Dispose'的別名 - 它釋放你的進程句柄副本而不是關閉正在運行的進程。 – 2010-07-01 11:06:04

1

由於這是Excel中,怎麼樣其實說話的Excel,並要求它關閉得好嗎?你可以使用COM來做到這一點。

+0

說我想很好地關閉DataSheet.xls。我如何使用COM來做到這一點?任何代碼示例? – Rabin 2010-07-01 11:05:29

+0

請參閱@ [GenericTypeTea](http://stackoverflow.com/users/44269/generictypetea)的[answer](http://stackoverflow.com/questions/3157051/better-option-than-process-kill/3157061 #3157061)。 – 2010-07-01 11:31:41