Opening an Excel file in C# using Process.Start

11,658

Normally, Process.Start(@"C:\Users\username\Documents\newTest.xlsx"); would open your document in Excel.

However, you say in a comment that you are doing this from an Excel add-in which runs in the background. The solution needs to take this into account (the code sample assumes that you have a VSTO add-in, otherwise you need to adjust accordingly):

// make the running Excel instance visible
Globals.ThisAddIn.Application.Visible = true;

// open the workbook using Excel interop
Globals.ThisAddIn.Application.Workbooks.Open(fileName);
Share:
11,658
Craig Gallagher
Author by

Craig Gallagher

A student at the Institute of Technology Sligo currently in my final year of studying Software Development.

Updated on June 15, 2022

Comments

  • Craig Gallagher
    Craig Gallagher almost 2 years

    I'm trying to open an excel file using a button click. And for some reason it's not working. I've tried several things. Any ideas why they are not working?

    Method 1 I have tried. This opens the file manager but does not open the proper file. It is definitely using the proper path to the file and the file does exist

    private string fileCopy;
    
    public RepairResultsControl()
    {
        InitializeComponent();
    }
    
    public void Show(PSRepair.AnalysisResults analysis, string pathNameCopy)
    {
        fileCopy = pathNameCopy;
        Show();
    }
    
    private void btnGoToFile_Click(object sender, EventArgs e)
    {
        Process.Start("explorer.exe", "/select,"+ fileCopy);
    }
    

    Method 2. This just didn't open anything not sure why

    System.Diagnostics.Process.Start(@"C:\Users\username\Documents\newTest.xlsx");
    
  • Shimmy Weitzhandler
    Shimmy Weitzhandler over 4 years
    I'm trying to open the xlsx file directly, and getting this exception: Win32Exception: The specified executable is not a valid application for this OS platform.
  • Dirk Vollmar
    Dirk Vollmar over 4 years
    This depends likely on the value of the UseShellExecute property. Make sure it is set to true.
  • Shimmy Weitzhandler
    Shimmy Weitzhandler over 4 years
    I was talking about Process.Start.
  • Dirk Vollmar
    Dirk Vollmar over 4 years
    Yes, pass in a ProcessStartInfo with that property set to true. If it still fails, you probably need to repair Office.