在Workbook取消激活完成后引发事件

时间:2017-04-05 15:15:57

标签: c# excel interop openxml excel-interop

我试图在WokbookDeactivate事件结束后触发事件,因为我需要在文件中写入一些元数据,只有在Excel文件完全关闭时才能完成。

使用WokbookDeactivate时,工作簿仍然显示为活动状态,如果我尝试运行访问excel文件的代码,则会引发异常"正在被另一个进程使用..."

ThisAddin_Startup

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
    this.Application.WorkbookDeactivate += Application_WorkbookDeactivate;
}

事件处理程序

void Application_WorkbookDeactivate(Microsoft.Office.Interop.Excel.Workbook Wb)
{
    Excel.Application excelApp = this.Application;
    string filePath = excelApp.ActiveWorkbook.FullName;
    string userName = GeneralFunctions.getUser();

    try
    {
        if (File.Exists(filePath) && Metadata.ContainsKey(filePath) && Metadata[filePath])
        {
            Metadata.Remove(filePath);
        }
    }
    catch (Exception)
    {

        throw;
    }
    finally
    {

    }
}

停用后我需要运行另一个事件来检查是否从元数据中删除了excel文件的密钥。这意味着我可以使用OpenXML函数编辑文档......

我尝试将两个事件附加到Deactivate,但是当第一个事件完成时,excel工作簿仍处于打开状态。

有什么想法吗?

另一种方法: 我创建了一个Timer属性System.Timers.Timer _tm;并调用一个方法来初始化它。

void Application_WorkbookDeactivate(Excel.Workbook Wb)
{
    Excel.Application excelApp = this.Application;
    string filePath = excelApp.ActiveWorkbook.FullName;

    try
    {
        if (File.Exists(filePath) && Metadata.ContainsKey(filePath) && Metadata[filePath] && Wb.FullName.Equals(filePath))
        {
            StartWrite(filePath);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

private void StartWrite(string filePath)
{
    _tm = new System.Timers.Timer(2000);
    _tm.Elapsed += (sender, args) => _tm_Elapsed(sender, filePath);
    _tm.Enabled = true;
}

void _tm_Elapsed(object sender, string filePath)
{
    try
    {
        ((System.Timers.Timer)sender).Enabled = false;
        string userName = GeneralFunctions.getUser();
        if (this.Application != null && Metadata[filePath])
        {
            // Do stuff with the file
            _tm.Stop();
        }
    }
    catch (Exception)
    {

        throw;
    }
}

0 个答案:

没有答案
相关问题