Wednesday, 4 December 2013

Running Excel Macros from ASP.Net

Today i want to show you how to execute excel macros using asp.net.

First of all we have to add reference to Mirosoft.Office.Interop.Excel dll in Visual studio.
Call the below method to execute macro.


void RunMacro()
{
string excelFile=@"C:\Users\ExMacro.xls";
Microsoft.Office.Interop.Excel.Application excel = Server.CreateObject("Excel.Application") as Microsoft.Office.Interop.Excel.Application;
excel.Visible = false;
Microsoft.Office.Interop.Excel.Workbooks wb = excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = wb.Open(excelFile);
Microsoft.Office.Interop.Excel.Worksheet sheet = book.Sheets[1];
excel.Application.DisplayAlerts = false;
//to hide all the messageboxes (if any)
excel.Run("Initiate_Process"); //Initiate_process is macro name.
book.Save();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}


Note: On Some servers to run excel marcos we have to add a folder by the name "desktop" in C:\Windows\SysWOW64\config\systemprofile (if your server is 64 bit) in C:\Windows\System32\config\systemprofile (if your server is 32 bit).
Crazy bug i say:).


The code is simple and self explanatory. First we created Application object and instantiated Workbooks. Using Workbooks reference we opened our sheet by uisng Open method and called Run method to run required macro. Finally we have released all of our objects using ReleaseComObject() method.
, , , ,

No comments:

Post a Comment