Solved

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

Posted on 2012-03-13
8
483 Views
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";
    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
0
Comment
Question by:Split_Pin
  • 4
  • 2
  • 2
8 Comments
 
LVL 28

Expert Comment

by:pepr
Comment Utility
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
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
Comment Utility
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
 
LVL 86

Expert Comment

by:jkr
Comment Utility
*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
 
LVL 28

Expert Comment

by:pepr
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 86

Expert Comment

by:jkr
Comment Utility
Well, at this stage I'd rather call it a "suggestion" than a "solution" ;o)
0
 

Author Comment

by:Split_Pin
Comment Utility
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
 

Author Closing Comment

by:Split_Pin
Comment Utility
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
 
LVL 28

Expert Comment

by:pepr
Comment Utility
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now