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

Posted on 2012-03-13
Last Modified: 2012-03-17
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";, ios::in);
    if (fin.is_open()) {
    // excel file is opened
		cout << "FILE IS OPEN";
    } else {
  cout << "Failed To Open File" << endl;

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
Question by:Split_Pin
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
LVL 29

Expert Comment

ID: 37714656
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...
LVL 29

Accepted Solution

pepr earned 500 total points
ID: 37715295
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.

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

    // 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 = NULL;
    spWorkbooks = NULL;

    spExcel = NULL;

    // Stop working with COM components.
    return 0;

Open in new window
LVL 86

Expert Comment

ID: 37715474



Open in new window

come close? The above would open the file with Excel...
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 29

Expert Comment

ID: 37715488
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.
LVL 86

Expert Comment

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

Author Comment

ID: 37719421
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 Closing Comment

ID: 37731605
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 :-)
LVL 29

Expert Comment

ID: 37733704
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.

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question