比Process.Kill()更好的选择

时间:2010-07-01 10:47:28

标签: c# visual-studio-2005

有没有比杀死()归档相同结果的流程更好的方法。当我杀死()Excel进程时,下次打开任何Excel工作表时,会打开“文档恢复”侧边栏,我不想这样做。

4 个答案:

答案 0 :(得分:5)

Microsoft.Office.Interop.Excel添加.Net引用。然后看看下面我敲了一下的代码:

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);

}

答案 1 :(得分:2)

不确定这是否有助于在Web浏览器中运行Excel。如果您可以获取正在运行的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... 
}

答案 2 :(得分:1)

由于这是Excel,如何实际与Excel交谈并要求它很好地关闭?您可以使用COM执行此操作。

答案 3 :(得分:0)

选项可以是Process.CloseMainWindow()