c#.net interop beforesave not firing

时间:2012-06-08 19:50:15

标签: c# .net excel visual-studio-addins excel-interop

基本上我想创建一个excel管理软件,客户可以将excel文件直接保存到数据库中。为了实现这一点,我试图用某个模板或文件打开一个excel工作表,然后让用户修改它,当用户保存他们的工作时,它会自动将excel程序保存到数据库中。

所以我到目前为止所做的是在保存之前测试事件并且它没有触发:

    static void Main()
    {
        System.Windows.Forms.Application.EnableVisualStyles();
        System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
        //Application.Run(new LoginForm());

        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

        Microsoft.Office.Interop.Excel.Application a = new 
                              Microsoft.Office.Interop.Excel.Application();


        Workbook wb = a.Workbooks.Open("\\\\doctor-pc\\excel\\test1.xlsx", 
                  Type.Missing, false, 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.BeforeSave += new WorkbookEvents_BeforeSaveEventHandler(wb_BeforeSave);

        a.Visible = true;

    }

    static void wb_BeforeSave(bool SaveAsUI, ref bool Cancel)
    {
        MessageBox.Show("Save");
    }

有人可以帮我这个吗?

我无法使用app level addin,因为我只希望行为影响程序打开的文档,而且我不能使用文档级别添加,因为程序可能会打开很多种类的文件和模板。

1 个答案:

答案 0 :(得分:2)

  1. 您需要维护对wb变量的实时引用(例如,通过将其提升为字段)。如果Workbook实例超出范围并被垃圾收集,那么它的事件永远不会被触发。

  2. 您需要保持.NET应用程序处于打开状态才能接收和处理BeforeSave事件。您可以通过创建EventWaitHandle来阻止Main方法直到wb_BeforeSave事件处理程序发出信号来实现此目的。