Question

How to read/write data into excel 2007 in c++?

Was it helpful?

Solution

Excel provides COM interface which you can use from your C++ application.

I have experience with Excel 2003 only but I think for excel 2007 it will also work.

This can be done e.g. with #import or in the way described in this article: http://support.microsoft.com/kb/216686

OTHER TIPS

There is a python solution (using COM dispatch) here: http://snippets.dzone.com/posts/show/2036

It's not C++, but the COM interface should be the same no matter which language you use, right?

You wouldn't need to port everything. Just __init__, set_range, get_value, set_value, save (or save_as), close, and quit. You might also need to dispose of garbage (as python has automatic gc).

Or you could just port (and modify) the following code (which I haven't tested, as I don't have excel anymore - you should probably check it by downloading python and pythonwin):

from win32com.client import Dispatch
app = Dispatch("Excel.Application")
app.Visible = True # spooky - watch the app run on your desktop!
app.Workbooks.Open("C:\\book.xls")

range = app.ActiveWorkbook.Sheets(1).Range("a1") 
print 'The range was:'
print range.Value

range.Value = 42

print 'The value is now 42'  

app.ActiveWorkbook.Save()
app.ActiveWorkbook.SaveAs("C:\\excel2.xls")

app.ActiveWorkbook.Close()
app.Quit()

# any gc to do?

Excel 2007 files are simply zip files. Try to rename .xlsx to .zip: you can extract files and folders. With a text editor you can view that they are all XML files.

So the solution:

  1. use a common class to unzip your xlsx
  2. use an xml parser to grab you data
  3. if you have modified somethig, re-zip all

No COM object required. Depending on your c++ compiler you can easyly find the required sources.

There are three main things you need to do.

1) Ensure pre-requisite files are installed and locatable.

Blindingly obvious I know, but make sure you have a suitable version of Excel installed, so that you can locate the required Microsoft libraries (and their locations). namely MSO.DLL, VBE6EXT.OLB and EXCEL.EXE

2) Set up the Microsoft libraries.

In your C++ code, let's say you start with a simple console application, be sure to include the import libraries in any C++ application that interfaces with Excel. In my example I use:

#import "C:\\Program Files (x86)\\Common Files\\microsoft shared\\OFFICE11\\MSO.DLL" \
rename( "RGB", "MSORGB" )

using namespace Office;  

#import "C:\\Program Files (x86)\\Common Files\\microsoft shared\\VBA\\VBA6\\VBE6EXT.OLB"  

using namespace VBIDE;  

#import "C:\\Program Files (x86)\\Microsoft Office\\OFFICE11\\EXCEL.EXE" \  
    rename( "DialogBox", "ExcelDialogBox" ) \  
    rename( "RGB", "ExcelRGB" ) \  
    rename( "CopyFile", "ExcelCopyFile" ) \  
    rename( "ReplaceText", "ExcelReplaceText" ) \  
    exclude( "IFont", "IPicture" ) no_dual_interfaces 

3) Use the Excel Object Model in your C++ code

For example, to declare an Excel Application Object pointer for reading / writing an Excel Workbook:

Excel::_ApplicationPtr pXL;  
pXL->Workbooks->Open( L"C:\\dump\\book.xls" );

And to access and manipulate the Excel Worksheet and the cells within it:

Excel::_WorksheetPtr pWksheet = pXL->ActiveSheet;  
Excel::RangePtr pRange = pWksheet->Cells;  
double value = pRange->Item[1][1];  
pRange->Item[1][1] = 5.4321; 

And so on. I have a more in-depth discussion at this following blog posting.

A low tech way I have used on a couple of projects is to make a simple script/macro/whatever that runs an external program. Write that external program in C++. Get that external program to read its input from and write its output to a .csv file (simple comma separated value text file). Excel can easily read and write .csv files, so this setup gives you everything you need to craft a viable solution.

This can all be done via the IDispatch interface. It can get really bloody complicated quickly (Cheers Microsoft) but at least once you've got your head round Excel you'll find integrating with any other MS application easy too :)

Fortunately there is someone over on codeguru who has made the process nice and easy. Once I'd read through that code I started to get my head round what excel was doing and, furthermore, i found it became REALLY easy to extend it to do other things that I wanted. Just remember that you are sending commands to Excel via the IDispatch interface. This means you need to think about how YOU would do something to figure out how to do it programatically.

Edit: the code guru example is for Excel 2003 but it should be fairly easy to extend it to 2007 :)

Start here with the OpenXml Sdk. Download the SDK from here. The SDK uses .NET, so you might need to use C++.NET

It has been a very long time but I have used the Jet OLEDB to get at Excel files. You might start searching in that direction.

I have used a 3rd Party component for this in the past: OLE XlsFile from SM Software (not free, but inexpensive). The advantage of this component over the Microsoft COM components is that you can use it to write XLS files even if Excel is not installed.

It also allows you to create speadsheets or workbooks with embedded formulas and formatting, something not possible if you use CSV files as an interchange format.

If you need the best performance, writing binary Excel files is the way to go and writing them is not as difficult as reading them. The binary file format is relatively well documented by the OpenOffice.org project:

http://sc.openoffice.org/excelfileformat.pdf

and Microsoft has also released the documentation:

http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Excel97-2007BinaryFileFormat(xls)Specification.xps

This solution will work best if you have to write many Excel files, mostly with data and little formatting, and if you don't want to open the files at the same time. If you write a single Excel file to open it afterwards, you can probably use the propsed C++ COM Interface as the other posters have explained.

Using the COM interface will necessitate expensive out-of-process calls unless you write an Excel COM Addin. If you write an Addin that imports your data into the current Excel sheet, filling the sheet will still be much slower than dumping a file, but for a single file at a time this can be acceptable depending on your user scenario. If you do decide to use the COM interface, minimize the number of calls to Excel. Use the methods that allow to insert an array of values if they exist, set style properties by row and column is possible and not per cell.

You can use ODBC to read and write data from an excel file easily without Excel. The link:Here

The link for how to write data using odbc: Here

I've used a set of C++ classes that is available from CodeProject before to write to XLS files.

It's really easy to use, and free! You can find it here.

Took me no time to set up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top