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?

2
  • Excel is a separate process, it has its own default directory. Commented Aug 10, 2015 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. Commented Aug 12, 2015 at 20:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Instead of Location property it's better to use CodeBase. Read this answer and the comments on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.