0

I am quite new to C++/CLI, and I am having trouble with opening an Excel file. This is my following code sample.

#using <system.dll>

using namespace System;
using namespace Microsoft::Office::Interop::Excel;

String ^filename = gcnew String(L"Test.xlsx");
try
{
    Application^ exapp = gcnew ApplicationClass();
    Workbook^ wb = exapp->Workbooks->Open(filename,  Type::Missing, Type::Missing,
        Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing,
        Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing,
        Type::Missing, Type::Missing);
    Worksheet^  exws = safe_cast<Worksheet^>(exapp->ActiveSheet);
    exws->Cells[1, 1] = "Hello world";
    return true;
    Console::WriteLine("File Read Successfully");
}
catch (Exception ^e)
{
    Console::WriteLine("Failed to read File");
    Console::WriteLine(e);
    return false;
};

Whenever I run it, it will always throw FileNotFoundException, even though the Excel file is right next to Test.exe, unless I change filename back to fullpath like C:\Users\NGU0085\Documents\Visual Studio 2013\Projects\Test\Debug\Test.xlsx

Is there any way to open an Excel file using relative path?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Trian Etymes
  • 69
  • 2
  • 8
  • Excel is a separate process, it has its own default directory. – Hans Passant Aug 10 '15 at 10:46
  • Are you running into this problem all the time, or only when you are debugging from the studio? If so, just change your program working directory under Project Properties->Configuration Properties -> Debugging to the correct path. – S. Larws Aug 12 '15 at 20:16

2 Answers2

1

Maybe the current directory is not set to what you expect. Current directory can change without you explicitly changing it in your code, so you shouldn't really rely on it being what you expect.

The solution is to turn your relative path to absolute path. Get app's directory using this answer, and add "Test.xlsx" to that path.

Community
  • 1
  • 1
Dialecticus
  • 16,400
  • 7
  • 43
  • 103
0

you can use this function System.Reflection.Assembly.GetExecutingAssembly().Location

Prasaathviki
  • 1,147
  • 2
  • 11
  • 22
  • Instead of `Location` property it's better to use `CodeBase`. Read this [answer](http://stackoverflow.com/a/837501/395718) and the comments on it. – Dialecticus Aug 11 '15 at 09:22