两种方式判断office 版本:
1通过 Microsoft.Office.Interop.Excel.dll 进行判断;
/// <summary>
/// 判断本机的Office版本,并返回后缀名
/// 需要引用 Microsoft.Office.Interop.Excel.dll
/// </summary>
/// <param name="strEx">返回后缀名</param>
/// <returns>true:office03;false:office07及以上</returns>
public static bool ExcelVersion(out string strEx)
{
bool bOffice03 = true;
Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
string Version = xlapp.Version;//获取你使用的excel 的版本号
if (Convert.ToDouble(Version) < 12)//You use Excel 97-2003
{
strEx = ".xls";
}
else//you use excel 2007 or later
{
strEx = ".xlsx";
bOffice03 = false;
}
return bOffice03;
}
2、通过注册表判断office版本
/// <summary>
/// 通过注册表检测office版本
/// </summary>
/// <param name="OfficeVersion">储存office版本的字符串</param>
/// <returns></returns>
public static bool OfficeIsInstall(out string OfficeVersion)
{
OfficeVersion = "";
Microsoft.Win32.RegistryKey regKey = null;
Microsoft.Win32.RegistryKey regSubKey1 = null;
Microsoft.Win32.RegistryKey regSubKey2 = null;
Microsoft.Win32.RegistryKey regSubKey3 = null;
Microsoft.Win32.RegistryKey regSubKey4 = null;
regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
regSubKey1 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Common\InstallRoot", false);
regSubKey2 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\InstallRoot", false);
regSubKey3 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot", false);
regSubKey4 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\15.0\Common\InstallRoot", false);
if (regSubKey4 != null && regSubKey4.GetValue("Path") != null)
{ OfficeVersion = "2013"; return true; }
else if (regSubKey3 != null && regSubKey3.GetValue("Path") != null)
{ OfficeVersion = "2010"; return true; }
else if (regSubKey2 != null && regSubKey2.GetValue("Path") != null)
{ OfficeVersion = "2007"; return true; }
else if (regSubKey1 != null && regSubKey1.GetValue("Path") != null)
{ OfficeVersion = "2003"; return true; }
else
{
regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
regSubKey1 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Common\InstallRoot", false);
regSubKey2 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\InstallRoot", false);
regSubKey3 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot", false);
regSubKey4 = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\15.0\Common\InstallRoot", false);
if (regSubKey4 != null && regSubKey4.GetValue("Path") != null)
{ OfficeVersion = "2013"; return true; }
else if (regSubKey3 != null && regSubKey3.GetValue("Path") != null)
{ OfficeVersion = "2010"; return true; }
else if (regSubKey2 != null && regSubKey2.GetValue("Path") != null)
{ OfficeVersion = "2007"; return true; }
else if (regSubKey1 != null && regSubKey1.GetValue("Path") != null)
{ OfficeVersion = "2003"; return true; }
else { return false; }
}
}
Excel导入导出时候,需要根据本机的Office版本来进行,否则导出文件后打开提示“文件格式与扩展名指定格式不一致”。