C++ to Actually Open an Excel File (So I can see it).

Hi experts,
I am just having a muck around with C++ (Visual Studio) for my own personal development. (Been playing with VB and VBA for too long at the office and I figure its time to see a bit more of the world!)

I'd like to see if I can use C++ to open an excel file (actually launch it so user can see it in excel). Struggling to find any relevant material on the web that I can make sense of.

So far I have the following (it seems to be finding the right file, though I can't see any excel windows, and it seems to think the file is "open" even though I know it is password protected - so it would at best have made it as far as "enter password".

[Sorry I forgot where I copied this from - either MSDN or codeproject or somewhere, it's not my work.]
#include "stdafx.h"
#include <fstream>
#include <iostream>
     
    using namespace std;
     
    int main(int argc, char **argv)
    {
    fstream fin;
    std::string excel_file = "c:\\Test\\Test.xlsx";
    fin.open(excel_file.c_str(), ios::in);
     
    if (fin.is_open()) {
    // excel file is opened
		cout << "FILE IS OPEN";
    fin.close();
    } else {
  cout << "Failed To Open File" << endl;
    }
	system("pause");
    }

Open in new window


If there is a way to do this with a small console application that would make sense to a beginner who is half way through their first book on C++ that would be great!

Cheers, Adrian
Split_PinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
The Excel file is a binary file.  I do recommend to open it via the MS Excel itself (this is what you probably mean by "launch the Excel file").  For that purpose, you have to have the MS Excel installed on the machine.  Then you can use the MS Excel components to open the Excel file.  Basically, you do control the Excel programmatically.  I am going to dig my old files to show some trivial working examples...
0
peprCommented:
Warning:  Office programming is unrelated to C++.  You should understand what the COM is and how the object model of the Office applications works.

Try the attached example to open the Excel with the hardwired file name.  The code is shown also here:

#import "Microsoft Shared\OFFICE12\MSO.DLL"\
        rename("DocumentProperties", "DocumentPropertiesMSO")\
        rename("SearchPath", "SearchPathMSO")\
        rename("RGB", "RBGMSO")

#import "Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
       
#import "Microsoft Office\Office12\EXCEL.EXE"\
        rename("DialogBox", "DialogBoxXL")\
        rename("RGB", "RBGXL")\
        rename("ReplaceText", "ReplaceTextXL")\
        rename("CopyFile", "CopyFileXL")\
        exclude("IFont", "IPicture")

#include <cassert>

using namespace std;

int main()
{
    // Start working with COM components.
    CoInitialize(0);

    // Launch the Excel.
    Excel::_ApplicationPtr spExcel;
    HRESULT hr = spExcel.CreateInstance(OLESTR("Excel.Application"));
    assert(SUCCEEDED(hr));

    // Prepare the filename to be opened.
    _variant_t vtFileName(OLESTR("c:\\Test\\Test.xlsx"));

    // Ask the Excel for the Workbooks object -- collection of all opened books.
    Excel::WorkbooksPtr spWorkbooks = spExcel->GetWorkbooks();

    // Open the Excel file and get the new workbook.
    Excel::_WorkbookPtr spBook = spWorkbooks->Open(_bstr_t(vtFileName));

    // Make the Excel application visible.
    spExcel->PutVisible(0, TRUE);  // 0 = simplification for lcid

    // Give up the objects -- let the Excel application open.
    spBook = NULL;
    spWorkbooks = NULL;
    spExcel = NULL;


/*  The commented-out code below closes everything, including the Excel application.
   
    spBook->Close(); 
    spBook = NULL;
    spWorkbooks = NULL;

    spExcel->Quit();
    spExcel = NULL;
*/

    // Stop working with COM components.
    CoUninitialize();
    return 0;
}

Open in new window

OpenExcelWithFile.zip
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jkrCommented:
*scratchingmyhead*

Would

ShellExecute(NULL,_T("open"),_T("c:\\Test\\Test.xlsx"),NULL,NULL,SW_SHOW);

Open in new window


come close? The above would open the file with Excel...
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

peprCommented:
I second for jkr's solution if the only wanted thing is to launch the application that is registered in the OS for the extension.  If you need to manipulate the content of the file (create or modify a file), then you should use the Excel components.
0
jkrCommented:
Well, at this stage I'd rather call it a "suggestion" than a "solution" ;o)
0
Split_PinAuthor Commented:
HI experts,
Many thanks - I have tried to implement but my brain is fried today. WIll report back once I've had a crack at both.
Cheers, Adrian
0
Split_PinAuthor Commented:
Must confess I am not able to get a proper grip on this just now, I think this was a bit more than I can chew. Many thanks however :-)
0
peprCommented:
Split_Pin, I can imagine your situation as it is probably the same with everyone who had to tackle with the problem.

The #import command is MS specific.  It takes the file and generates the .tlh and .tli files (a Type Library Header and TL Implementation C++ files -- the interface to the COM objects implemented by the DLL or the like file.  The rename part is only to avoid clashes with other libraries -- just tried by other people, copy/pasted from other sources.

Starting from the Excel::_ApplicationPtr spExcel; you are using the classes and object from the above mentioned .tlh and .tli files.  They wrap the raw calls of the COM components.

It is all not that difficult, but it is quite a lot of things to be learned (partly the principles but also a quantity of knowledge related to the objects used internally by the Excel).

Thanks for the points.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.