-
-
Save sweetcard/881c4d33fd8c9a2b4462c9b6cb8dbc87 to your computer and use it in GitHub Desktop.
Excel-DNA Dynamic Code from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<DnaLibrary Name="ExcelDna Test Dynamic Method" Language="C#"> | |
<Reference Name="System.Windows.Forms" /> | |
<![CDATA[ | |
using System; | |
using System.CodeDom.Compiler; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Reflection; | |
using System.Windows.Forms; | |
using Microsoft.CSharp; | |
using ExcelDna.Integration; | |
public class Test : IExcelAddIn | |
{ | |
// Just to test that we are loaded. | |
public static double MyAdd(double d1, double d2) | |
{ | |
return d1 + d2; | |
} | |
public void AutoOpen() | |
{ | |
RegisterMyClass(); | |
} | |
public void AutoClose() | |
{ | |
} | |
private void RegisterMyClass() | |
{ | |
string code = | |
@" | |
public class Script | |
{ | |
public static double MyDynamicAdd(double d1, double d2) | |
{ | |
return d1 + d2; | |
} | |
}"; | |
CompilerParameters cp = new CompilerParameters(); | |
cp.GenerateExecutable = false; | |
cp.GenerateInMemory = true; | |
cp.TreatWarningsAsErrors = false; | |
cp.ReferencedAssemblies.Add("System.dll"); //, "System.Windows.Forms.dll", "ExcelDna.Integration.dll" ); | |
CSharpCodeProvider provider = new CSharpCodeProvider(); | |
CompilerResults cr = provider.CompileAssemblyFromSource(cp, new string[] { code }); | |
if (!cr.Errors.HasErrors) | |
{ | |
Assembly asm = cr.CompiledAssembly; | |
Type[] types = asm.GetTypes(); | |
List<MethodInfo> methods = new List<MethodInfo>(); | |
// Get list of MethodInfo's from assembly for each method with ExcelFunction attribute | |
foreach (Type type in types) | |
{ | |
foreach (MethodInfo info in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) | |
{ | |
// foreach (Attribute attr in info.GetCustomAttributes(false)) | |
// { | |
// Type attribType = attr.GetType(); | |
// if (attribType.FullName == "ExcelDna.Integration.ExcelFunctionAttribute" || | |
// attribType.FullName == "ExcelDna.Integration.ExcelCommmandAttribute" ) | |
// { | |
methods.Add(info); | |
// } | |
// } | |
} | |
} | |
Integration.RegisterMethods(methods); | |
} | |
else | |
{ | |
MessageBox.Show("Errors during compile!"); | |
} | |
} | |
} | |
]]> | |
</DnaLibrary> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment