Qt导出Excel的简单实现

     QAxObject对COM对象进行了封装,QAxObject派生自QAxBase,而后者提供了一组API通过IUnknown(不清楚IUnknown的同学可以去看看COM对象模型)指针直接访问COM对象,我们这里讲的excel也是一个COM对象,因此我们可以通过QAxObject来操作它,为了便于理解,我们首先了解一下excel的对象的主要层次结构:

                                                  


    上图是excel对象的层次结构,1个excel就有1个Application对象,1个Application对象由多个Workbook对象组成,这些Workbook对象由Workbooks对象统一管理,Workbook对象下可以包含若干个Worksheet,这些Worksheet对象也有一个WorkSheets对象来统一管理,接下来是Range对象,这个对象就对应Worksheet里的表格单元了,好了大家应该清楚了Excel的对象的主要层次结构了吧,下面我们来看看QAxObject是怎么来导出excel的:

1.新建一个excel

QAxObject *pApplication = NULL;
QAxObject *pWorkBooks = NULL;
QAxObject *pWorkBook = NULL;
QAxObject *pSheets = NULL;
QAxObject *pSheet = NULL;
void newExcel(const QString &fileName)
{
    pApplication = new QAxObject();
    pApplication->setControl("Excel.Application");//连接Excel控件
    pApplication->dynamicCall("SetVisible(bool)", false);//false不显示窗体
    pApplication->setProperty("DisplayAlerts", false);//不显示任何警告信息。
    pWorkBooks = pApplication->querySubObject("Workbooks");
    QFile file(fileName);
    if (file.exists())
    {
        pWorkBook = pWorkBooks->querySubObject("Open(const QString &)", fileName);
    }
    else
    {
        pWorkBooks->dynamicCall("Add");
        pWorkBook = pApplication->querySubObject("ActiveWorkBook");
    }
    pSheets = pWorkBook->querySubObject("Sheets");
    pSheet = pSheets->querySubObject("Item(int)", 1);
}

2.增加1个Worksheet

void appendSheet(const QString &sheetName)
{
    QAxObject *pLastSheet = pSheets->querySubObject("Item(int)", cnt);
    pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant());
    pSheet = pSheets->querySubObject("Item(int)", cnt);
    pLastSheet->dynamicCall("Move(QVariant)", pSheet->asVariant());
    pSheet->setProperty("Name", sheetName);
}

3.向Excel单元格中写入数据

void setCellValue(int row, int column, const QString &value)
{
    QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column);
    range->dynamicCall("Value", value);
}

4.保存Excel

void saveExcel(constQString &fileName)

{
    pWorkBook->dynamicCall("SaveAs(const QString &)",
                           QDir::toNativeSeparators(fileName));
}

5.释放Excel

void  freeExcel()

{
    if (pApplication != NULL)
    {
        pApplication->dynamicCall("Quit()");
        delete pApplication;
        pApplication = NULL;
    }
}

你可能感兴趣的:(技术)