1

Basically I want to create an excel management software, where clients can save their excel files directly to the database. In order to achieve this, I'm trying to open up an excel worksheet with a certain template or file, and then let the user modify it, and when the user saves their work, it will automatically save the excel program into the database.

So what I've done so far is to test the event before save and it is not firing:

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

Can someone help me with this?

I cant use app level addin because I only want the behavior to affect the document opened by the program, and I can't use document level add in because the program may open a lot of varieties of files and templates.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Darius Suwardi
  • 127
  • 1
  • 4
  • 9

1 Answers1

2
  1. You need to maintain a live reference to your wb variable (for example, by promoting it to a field). If the Workbook instance goes out-of-scope and gets garbage-collected, then its events would never get fired.

  2. You need to keep your .NET application open in order to be able to receive and handle the BeforeSave event. You could achieve this by creating an EventWaitHandle that blocks the Main method until signalled by wb_BeforeSave event handler.

Douglas
  • 53,759
  • 13
  • 140
  • 188