如果您使用.NET 3.5,则不能使用dynamic
关键字。您唯一的选择是使用@Francesco所描述的一系列代理类(手动编写或自动生成)。但是,如果您需要访问大量Excel类/函数/属性,手动方法非常麻烦。你必须为你需要的每个成员编写一个函数/属性代理。
管理这一点的关键在于,不是编写大量的代理函数,而是将处理Excel的所有代码放在放置在不同库项目中的单独软件层(如数据访问层,DAL)中。该层仅向应用程序提供一些高级接口(只有少数成员函数),以至于应用程序甚至不知道MS Excel自动化的用法。
请注意,即使您不想动态加载程序集,此封装的Excel访问代码也是一种很好的做法。例如,如果您发现令人沮丧,您可以使用另一种技术(如ADO.NET)轻松替换Office Automation,并使用Microsoft.ACE.OLEDB.12.0
提供商reading from/writing to Excel files,这在x64平台内也令您感到沮丧!
例如,如果你想从一个Excel文件,抢板和数据,您可以提供姓名的人士称Utils.OfficeAutomation
一个项目,里面的以下接口(没有提及Microsoft.Office.Interop.Excel.dll
):
interface IExcelLayer {
...
bool ImportFrom(string fileName, string sheetName, out object[,] cells, bool skipHeaderRow = true);
// a few other members...
...
}
然后实现它命名为一个单独的项目,说Utils.OfficeAutomation.Impl
,其中引用了两个Utils.OfficeAutomation
和真实Microsoft.Office.Interop.Excel.dll
:
class ExcelMagician : IExcelLayer {
...
bool ImportFrom(string fileName, string sheetName, out object[,] cells, bool skipHeaderRow = true)
{
Excel.Application excelApp = new Excel.Application()
...
}
...
}
迈n应用程序仅提供Utils.OfficeAutomation
。作为回报,Utils.OfficeAutomation
是动态查找和加载Utils.OfficeAutomation.Impl
,或者如果出事了产生错误莫名其妙负责:
IExcelLayer m_instance = null;
...
try
{
Assembly assembly = Assembly.Load("Utils.OfficeAutomation.Impl");
Type excelType = assembly.GetType("Utils.OfficeAutomation.Impl.ExcelMagician");
m_instance = (IExcelLayer) Activator.CreateInstance(excelType);
}
catch (Exception e)
{
throw new Exception("Couldn't load Excel assembly.")
}
如果没有安装Microsoft Excel的一个合适的版本,可加载程序集Utils.OfficeAutomation.Impl
失败,或致电像ImportFrom
这样的成员会生成一个异常。
您最后需要在Utils.OfficeAutomation
内编写包装类作为Excel Access Layer或Excel功能的网关。
似乎你使用.NET 3.5而不是.net 4? –
此外,请检查此解决方法:http://www.codeproject.com/Articles/10888/SafeCOMWrapper-Managed-Disposable-Strongly-Typed-s –