Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


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

Posted on 2012-03-13
Medium Priority
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";
    fin.open(excel_file.c_str(), 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 2000 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...
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

636 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