需要使用C#.Net关闭工作簿或Excel工作表 [英] Need to close a workbook or excel sheet using C#.Net

查看:146
本文介绍了需要使用C#.Net关闭工作簿或Excel工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





在我的应用程序中,我使用第三方工具显示上传的Excel工作表并进行编辑和保存。在此过程中,我需要删除现有的Excel工作表并编辑和保存新的Excel工作表。我试图删除但是excel不会删除并抛出错误,因为excel表在使用时被另一个进程无法删除。所以我决定关闭excel表或者终止进程,所以我编写如下代码:

Hi,

In my application i am using a third party tool to show an uploaded excel sheet and to edit and save it. During this process i need to delete the existing excel sheet and edit and save new excel sheet. I have tried to delete but the excel will not delete and throw error as excel sheet in use by another process cannot delete. So i decided to close that excel sheet or kill the process so i wrote code as below:

using Excel = Microsoft.Office.Interop.Excel;







Excel.ApplicationClass _Excel;
Excel.Workbook WB;
Excel.Worksheet WS;







try
{

    _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
    WB = _Excel.Workbooks.Open(@"FIENAME",
        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);

    WB.Close(false , Type.Missing, Type.Missing);


    //do something

}
catch (Exception ex)
{
    WB.Close(false, Type.Missing, Type.Missing);

    throw;
}
finally
{
    GC.Collect();
    GC.WaitForPendingFinalizers();

    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);

    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);


}





但这仍然会产生与使用excel表相同的错误通过另一个过程...请你帮助我如何以编程方式关闭excel或工作簿。或者这可以有什么编程解决方案..因为杀戮过程可能会影响服务器中的其他项目...



请帮助!!提前感谢你!!



but this will still throw same error that the excel sheet is being used by another process... Can u please help me how can we close that excel or workbook programatically. Or what programatic solution this can have.. as killing process might effect other projects in Server...

Please help!! Thanking You in advance!!

推荐答案

首先,请阅读我对这个问题的评论,然后看看这里:从C#关闭excel工作簿 [ ^ ]
First of all, please, read my comment to the question, then have a look here: Closing excel workbook from C#[^]


这篇关于需要使用C#.Net关闭工作簿或Excel工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆