如何用C#得到本机上Excel的版本
1个回答
2017-05-11
展开全部
你可以选择读取文件目录和注册表的方式,但用户必须安装的是标准office,如果是精简版或者免安装版的就不可以。
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace RegistryUtil {
static class Program {
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string version = null;
string path = null;
GetOfficeInfo(out version, out path);
Console.WriteLine(string.Format("OFFICE 版本号:{0}, 安装路径:{1}", version, path));
}
/// <summary>
/// 获取注册表中的OFFICE版本和安装路径信息
/// </summary>
/// <param name="version">出参,版本号</param>
/// <param name="path">出参,安装路径</param>
/// <returns>int错误码</returns>
public static int GetOfficeInfo(out string version, out string path) {
path = string.Empty; // OFFICE安装路径
version = string.Empty; // OFFICE版本
int result = 0;
RegistryKey regKey = null;
try {
regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Excel.exe"); // Excel程序的注册表路径
string regValue = regKey.GetValue("Path").ToString();
string temp = regValue.Substring(0, regValue.Length - 1);
string versionName = temp.Substring(temp.LastIndexOf("\\") + 1);
switch (versionName) {
case "Office11": //检查本机是否安装Office2003
version = "Office2003";
break;
case "Office12": //检查本机是否安装Office2007
version = "Office2007";
break;
case "Office14": //检查本机是否安装Office2010
version = "Office2010";
break;
case "Office15": //检查本机是否安装Office2013
version = "Office2013";
break;
default:
version = "未知版本!";
break;
}
path = regValue;
} catch (Exception ex) {
result = -1;
Console.WriteLine(ex.Message);
} finally {
if (null != regKey) {
regKey.Close();
regKey = null;
}
}
return result;
}
}
}
或者这个(未测试代码是否可靠,请自行修改)
//判断本机是否安装Excel文件方法
private bool codeboolisExcelInstalled()
{
Type type = Type.GetTypeFromProgID("Excel.Application");
return type != null;
}
/// <summary>
/// Self_Variable:查询注册表某个键值是否存在
/// </summary>
/// <returns></returns>
public bool ExistsRegedit()
{
bool ifused = false;
RegistryKey rk = Registry.LocalMachine;
RegistryKey akey = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Word\\InstallRoot\\");
RegistryKey akeytwo = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Word\\InstallRoot\\");
//检查本机是否安装Office2003
if (akey != null)
{
string file03 = akey.GetValue("Path").ToString();
if (File.Exists(file03 + "Excel.exe"))
{
ifused = true;
}
}
//检查本机是否安装Office2007
if (akeytwo != null)
{
string file07 = akeytwo.GetValue("Path").ToString();
if (File.Exists(file07 + "Excel.exe"))
{
ifused = true;
}
}
return ifused;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询