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.
You need to maintain a live reference to your
wbvariable (for example, by promoting it to a field). If theWorkbookinstance goes out-of-scope and gets garbage-collected, then its events would never get fired.You need to keep your .NET application open in order to be able to receive and handle the
BeforeSaveevent. You could achieve this by creating anEventWaitHandlethat blocks theMainmethod until signalled bywb_BeforeSaveevent handler.