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.");
}
}
An innovative, experienced solutions architect with strong focus on public cloud architecture, solution design and leading technical team. Zhen has 15 years experience designing and implementing a wide spectrum of enterprise level solutions. In the last 4 years, he is committed to evangelising Azure, DevOps and Scrum. His recent focus are enterprise digitisation, cloud governance, reference architecture, IoT, Big Data, Microservices, AWS.
Monday, November 16, 2009
c# detect excel install location in registry and open file
Subscribe to:
Post Comments (Atom)
7 comments:
Hi
On Windows x64 the code might fail.
In that case also check the keys below SOFTWARE\Wow6432Node\MicroSoft\Office
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)
Great!
Thanks for sharing us. Microsoft Excel Training Courses Malaysia
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
I appreciated your work very thanks grammar checking
Thank you!
Post a Comment