Lahiru Chandima
Lahiru Chandima

Reputation: 24068

How to drive excel window from Qt application

In my Qt application, I have a window with a table which gets dynamically updated with data from a backend server. I need my window to be able to open an excel instance, insert all the data in the table to excel window and update the excel cells when data in my table gets updated.

Is this something that is possible to achieve? If so, how I can get this done? I do not mind a platform dependent solution which can only run on Windows.

Upvotes: 0

Views: 1284

Answers (1)

Lahiru Chandima
Lahiru Chandima

Reputation: 24068

This is the code I used finally.

Opening Excel:

QAxObject* excel = new QAxObject("Excel.Application", 0);
excel->dynamicCall("SetVisible(bool)", true);

Reading cell values:

QAxObject* workbooks = excel->querySubObject("Workbooks");
QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", "D:\\a.xlsx");
QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1);
QAxObject* usedrange = worksheet->querySubObject("UsedRange");
QAxObject* rows = usedrange->querySubObject("Rows");
QAxObject* columns = usedrange->querySubObject("Columns");
int intRowStart = usedrange->property("Row").toInt();
int intColStart = usedrange->property("Column").toInt();
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();
QAxObject* cell;
for (int i = intRowStart; i < intRowStart + intRows; i++)
{
    for (int j = intColStart; j < intColStart + intCols; j++)
    {
        cell = excel->querySubObject("Cells(Int, Int)", i, j);
        QVariant cellValue = cell->dynamicCall("value");
        qDebug() << cellValue.toString();
    } 
}

Writing cell values

cell->setProperty("Value", "somevalue");

Note: Remember to create QApplication before doing any of these. I spent a considerable amount of time figuring out what is wrong by not doing this.

Upvotes: 2

Related Questions