Home » excel » .net – Open and read Excel file with C++/CLI

.net – Open and read Excel file with C++/CLI

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to create a program with C++/CLI that reads some data from Excel workbooks using Visual Studio.
I have added Microsoft.Office.Interop.Excel (v12) to the references in the project properties.
My basic goal would be only to get a cell’s value as a string (the workbook contains only text values).
My current code is the following (only the main part is included of course):

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace Microsoft::Office::Interop::Excel;

start(void){
        Microsoft::Office::Interop::Excel::Application^ exApp= gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
        String^ filename="e:\test.xls";
        Workbook^ wb = exApp->Workbooks->Open(filename, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing, Type::Missing);
        Worksheet^  exWs  = safe_cast<Worksheet^>(exApp->ActiveSheet);
        int row=1;
        int col=1;
        String^ tmp=((Microsoft::Office::Interop::Excel::Range^)exWs->Cells[(System::Object^)row, (System::Object^)col])->Value2->ToString();
        MessageBox::Show(tmp);
}

When I run it, it crashes with the following error:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in exc2.exe

Additional information: Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))

It happens with both xls and xlsx files, when I try to open the workbook (at the line that starts with “Workbook^ wb = exApp->Workbooks->Open” – so I could not even check if the rest is working).
Could some help please, what do i miss/do wrong?

Thank you in advance.

How to&Answers:

Okay, i got the main problem finally, if anybody else runs into the same problem:

When opening an Excel file, the Windows’ and the installed Excel program’s regional settings have to be the same. I live in Hungary, with Hungarian regional settings in Windows [note: i use English Windows, just the regional settings differ], and I have an English version of Excel. Once I switched the regional settings in Windows to US [the same as the Excel’s region], cleaned and rebuilt the solution, everything started to work like a charm.

(I’m not sure if the messagebox part worked in my code, i changed it meanwhile, the main problem was opening the file)