Opening a pre-existing excel file

12.6k views Asked by At

I am trying to open a pre-existing excel file from a directory on my computer. However, I am getting a COMexception when my code gets to the Workbooks.Open method. I'm am unsure what I'm dong wrong. Any help is appreciated.

using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;

namespace Excel_Create
{
    class Program
    {

        static void Main(string[] args)
        {


            string mySheet = @"‪‪‪‪C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls";
              Excel.Application xlApp = new Excel.Application();
              xlApp.Visible = true;


              if (xlApp == null)
              {
                  MessageBox.Show("Excel is not properly installed!!");
                  return;
              }



         Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(mySheet,
          0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
          true, false, 0, true, false, false              );

        }
    }
}

Here is what the exception says: An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Excel_Create.exe

Additional information: '‪‪‪‪C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.

3

There are 3 answers

4
David On

I think you're having problems with the spaces in your file path.

Try this, instead:

string mySheet = @"""C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls""";
0
Daniel Taki On

Found a solution that worked for me :

     var mySheet = Path.Combine(Directory.GetCurrentDirectory(), "Sample.xlsx");
          Excel.Application xlApp = new Excel.Application();
          xlApp.Visible = true;


          if (xlApp == null)
          {
              MessageBox.Show("Excel is not properly installed!!");
              return;
          }

          try
          {
              Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(mySheet);

          }
          catch(Exception ex)
          {
              xlApp.Quit();

          }
0
tahir abbas On

you may try this ......

Excel.Application excelApp = 
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");