QT读取Excel 简单范例代码

#include
#include
#include
#include
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
 //   QAxSelect select;
 //   select.show();
    QAxWidget excel("Excel.Application");
    excel.setProperty("Visible", true);//显示当前窗口
    //excel.setProperty("Caption","Invoke Microsoft Excel");//更改标题栏
    QAxObject * workbooks = excel.querySubObject("WorkBooks");//获取excel的集合指针
    QAxObject *workbook = workbooks->querySubObject("Open (const QString &)",QString("c:/test.xls"));//打开指定路径的xls文档
    QAxObject * worksheets = workbook->querySubObject("WorkSheets");//获取sheets的集合指针
    int intCount = worksheets->property("Count").toInt();//获取sheets的数量
    for (int i = 1; i <= intCount; i++)
    {
        int intVal;
        QAxObject * worksheet = workbook->querySubObject("Worksheets(int)", i);//获取指定位置的sheet页面
        qDebug() << i << worksheet->property("Name").toString();
        QAxObject * range = worksheet->querySubObject("Cells(1,1)");//获取sheet页面中的C(1,1)数据
        intVal = range->property("Value").toInt();//保存该数据
        range->setProperty("Value", QVariant(intVal+1));//将数据加1并重新保存回C(1,1)
        QAxObject * range2 = worksheet->querySubObject("Range(C1)");//???????????
        intVal = range2->property("Value").toInt();
        range2->setProperty("Value", QVariant(intVal+1));
    }
    QAxObject * worksheet = workbook->querySubObject("Worksheets(int)", 1);//打开第一个sheet
    QAxObject * usedrange = worksheet->querySubObject("UsedRange");//获取该sheet的使用范围对象
    QAxObject * rows = usedrange->querySubObject("Rows");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intRowStart = usedrange->property("Row").toInt();
    qDebug() << intRowStart;
    int intColStart = usedrange->property("Column").toInt();
    qDebug() << intColStart;
    int intCols = columns->property("Count").toInt();
    int intRows = rows->property("Count").toInt();
    for (int i = intRowStart; i < intRowStart + intRows; i++)
    {
        for (int j = intColStart; j < intColStart + intCols; j++)
        {
            QAxObject * range = worksheet->querySubObject("Cells(int,int)", i, j );
            qDebug() << i << j << range->property("Value");
        }
    }
    excel.setProperty("DisplayAlerts", 0);
    workbook->dynamicCall("SaveAs (const QString&)", QString("c:/xlsbyqt.xls"));
    excel.setProperty("DisplayAlerts", 1);
    workbook->dynamicCall("Close (Boolean)", false);
    excel.dynamicCall("Quit (void)");
    return a.exec();
}

你可能感兴趣的:(QT)