在网站上编程执行远程计算机上的Excelmacros

我有一个网站,用户使用macros生成Excel报告,当我尝试在我的本地机器上运行它时,它生成完美,并在Excel中运行macros。 当我发布到服务器,同时我在那里login(RDP打开会话),并尝试从该服务器以外的浏览器运行,它也按预期运行。 当我在服务器(RDP)注销,然后在服务器之外的浏览器(即从我的机器)运行它时,问题发生macros不运行,但创build我的Excel。

这是我正在使用的代码

public class Report { protected Workbook Workbook { get; set; } protected Application Excel { get; set; } public void RunReport() { // Launch Excel on the server Excel = new Application { DisplayAlerts = false, ScreenUpdating = false, Visible = false }; // Load the workbook template Workbook = Excel.Workbooks.Open(@"D:\Book1.xlt"); // Execute macros that generates the report, if any ExecuteMacros(); Workbook.SaveAs(@"D:\Ray'sTesting.xls", XlFileFormat.xlExcel8); QuitExcel(); } private void QuitExcel() { if (Workbook != null) { Workbook.Close(false); Marshal.ReleaseComObject(Workbook); } if (Excel != null) { Excel.Quit(); Marshal.ReleaseComObject(Excel); } } private void ExecuteMacros() { const string legacyModuleName = "Module1"; const string legacyMacroName = "myMacro"; bool legacyMacroExists = false; try { var legacyMacroModule = Workbook.VBProject.VBComponents.Item(legacyModuleName); if (legacyMacroModule != null) { int legacyMacroStartLine = legacyMacroModule.CodeModule.ProcStartLine[legacyMacroName, Microsoft.Vbe.Interop.vbext_ProcKind.vbext_pk_Proc]; legacyMacroExists = legacyMacroStartLine > 0; } } catch (Exception) { legacyMacroExists = false; } if (!legacyMacroExists) { return; } // VBA code for the dynamic macro that calls the CI2 legacy macro var moduleCode = new StringBuilder(); moduleCode.AppendLine("Public Sub LaunchLegacyMacro()"); moduleCode.AppendLine(string.Format("{0}.{1}", legacyModuleName, legacyMacroName)); moduleCode.AppendLine("End Sub"); // Add the dynamic macro to the ThisWorkbook module var workbookMainModule = Workbook.VBProject.VBComponents.Item("ThisWorkbook"); workbookMainModule.CodeModule.AddFromString(moduleCode.ToString()); // Execute the dynamic macro Microsoft.VisualBasic.Interaction.CallByName(Workbook, "LaunchLegacyMacro", Microsoft.VisualBasic.CallType.Method, new object[] { }); } } 

每当我们运行excelmacros时,我都通过编辑registry来实现这个工作

 private static void ModifyExcelSecuritySettings() { // Make sure we have programmatic access to the project to run macros using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\14.0\Excel\Security", true)) { if (key != null) { if ((int)key.GetValue("AccessVBOM", 0) != 1) { key.SetValue("AccessVBOM", 1); } key.Close(); } } } 

所以代码应该像这样

 public void RunReport() { ModifyExcelSecuritySettings(); // Launch Excel on the server Excel = new Application { DisplayAlerts = false, ScreenUpdating = false, Visible = false }; ..... 

我还创build了一个博客文章,您可以在这里查看完整的解决scheme

http://anyrest.wordpress.com/2012/06/22/programmatic-execution-excel-macro-on-remote-machine-from-a-website/