Monday, November 16, 2009

c# detect excel install location in registry and open file

public void OpenInExcel(string filename)
{
string dir = "";
RegistryKey key = Registry.LocalMachine;
RegistryKey excelKey = key.OpenSubKey(@"SOFTWARE\MicroSoft\Office");
if (excelKey != null)
{
foreach (string valuename in excelKey.GetSubKeyNames())
{
int version = 9;
double currentVersion=0;
if (Double.TryParse(valuename, out currentVersion) && currentVersion >= version)
{
RegistryKey rootdir = excelKey.OpenSubKey(currentVersion + @".0\Excel\InstallRoot");
if (rootdir != null)
{
dir = rootdir.GetValue(rootdir.GetValueNames()[0]).ToString();
break;
}
}
}
}
if (dir != "")
{
ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.FileName = dir + @"Excel.exe";
startInfo.Arguments = "\"" + fileName + "\"";
startInfo.UseShellExecute = false;

using (Process process = new Process())
{
process.StartInfo = startInfo;
try
{
process.Start();
}
catch (Exception ex)
{
Console.WriteLine("\n\nCould not start Excel process.");
Console.WriteLine(ex);
}
}
}
else
{
MessageBox.Show("Can't Open in excel because excel is not installed.");
}
}

7 comments:

Anonymous said...

Hi

On Windows x64 the code might fail.

In that case also check the keys below SOFTWARE\Wow6432Node\MicroSoft\Office

Ovi said...

It works on x64 as well. Apparently excelKey.GetSubKeyNames() returns from both SOFTWARE\MicroSoft\Office and SOFTWARE\Wow6432Node\MicroSoft\Office

My problem was parsing the version as a double.
Since the computer culture considers , as decimal separator and . as thousands separator, I changed the if to:
if (Double.TryParse(valuename, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out currentVersion) && currentVersion >= version)

Hollis said...

Great!

navya said...

Great Article
C# Training in Chennai | C# Online Training | ASP.NET Training in Chennai

C# Training in Chennai | Dot Net Training in Chennai | Dot Net Training in Chennai

AKON said...

Thanks for sharing us. Microsoft Excel Training Courses Malaysia

GULO said...

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks for grammarly trial click here

IMF said...

I appreciated your work very thanks grammar checking