在编写Winform程序的时候发现,在开发环境的excel导入没问题,可是打包安装到客户机器上运行就出现了问题,找到问题原来是因为excel版本导致的问题,如果excel需要对应的excel版本dll支持,版本看代码switch
同时发现office的dll位置存放在:D:\Program Files\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA
经测试可运行,总结入下:
/// <summary>
/// 通过注册列表获取excel版本
/// </summary>
/// <returns></returns>
public string GetOfficePath()
{
string strVersionResult = "没有安装Office";
string path = "";
Microsoft.Win32.RegistryKey regKey = null;
Microsoft.Win32.RegistryKey regSubKey = null;
try
{
regKey = Microsoft.Win32.Registry.LocalMachine;
for (int i = 10; i <= 14; i++)
{
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\" + i + @".0\Common\InstallRoot", false);
if (regSubKey != null)
{
if (regSubKey.GetValue("Path") != null)
{
path = regSubKey.GetValue("Path").ToString();
if (regSubKey != null)
{
if (System.IO.File.Exists(path + "Excel.exe"))
{
switch (i)
{
case 11: return "office2003";
case 12: return "office2007";
case 14: return "office2010";
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new Exception("读取注册表出错!", ex);
}
return strVersionResult;
}