We help IT Professionals succeed at work.

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

Split_Pin
Split_Pin asked
on
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
Comment
Watch Question

CERTIFIED EXPERT

Commented:
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...
CERTIFIED EXPERT
Commented:
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
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
*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...
CERTIFIED EXPERT

Commented:
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.
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
Well, at this stage I'd rather call it a "suggestion" than a "solution" ;o)

Author

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

Author

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 :-)
CERTIFIED EXPERT

Commented:
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.