优化从Qt应用程序写入excel表的速度

时间:2014-12-26 06:00:42

标签: c++ excel qt

我想通过我的Qt应用程序向excel表写入相当大量的数据。我目前使用以下代码。

QAxObject* pExcel = new QAxObject("Excel.Application", 0);
QAxObject* pWorkbooks = pExcel->querySubObject("Workbooks");
QAxObject* pWorkbook = pWorkbooks->querySubObject("Open(const QString&)", s_FilePath);
QAxObject* pWorksheet = pWorkbook->querySubObject("Worksheets(int)", 1);

for (int i = 0; i < iColumnCount; ++i)
{
    for (int j = 0; j < iRowCount; ++j)
    {
        QAxObject* pCell = pWorksheet->querySubObject("Cells(Int, Int)", i + 1, j + 1);
        pCell->setProperty("Value", "somevalue");
    }
}

但是,pCell-&gt; setProperty()非常慢,以这种方式设置所有值需要很长时间。

有人知道更快地设置值的方法吗?

1 个答案:

答案 0 :(得分:0)

找到一种批量更新单元格的方法,方法是从this帖子一次更新一系列单元格,以解决问题。

以下是从帖子中复制的代码。

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

QAxObject *sheets = workbook->querySubObject( "Worksheets" );

QAxObject *sheet1 = sheets->querySubObject( "Item( int )", 1 );
sheet1->dynamicCall("SetName(const QString&)", QVariant(sheet1Name));

int n;
QList< QVariant> table;
for (int i=0; i<5; i++)
{
    QList row;
    for (int j=0; j<5; j++)
    {
    n = i*5+j;
    row.append(QVariant(n));
    }
    table.append(QVariant(row));
}

//get a 5x5 range of cells : from A1 to E5 
QAxObject *range = sheet1->querySubObject( "Range(const QString&, const QString&)", QString("A1"), QString("E5"));
QVariant vTable(table);
range->dynamicCall("SetValue(const QVariant&)", vTable);