Qt操作Excel文件知识总结

来源:互联网 发布:软件工程硕士学费 编辑:程序博客网 时间:2024/05/17 08:05

       

Qt在windows平台下封装了Activex,可以同VAB中操作Excel一样读取xls文件,因此不支持linux平台。现在这个功能在Qt4.7中也不需要额外的商业许可了。这种方法比较通用,是常规方法,缺点是速度太慢了,如果数据量大,要想提高速度,可以考虑把excel文件另存为csv格式,用逗号分割个单元格的文本方式,直接操作文本文件,速度很快

2011年12月16日,在开源网站搜到一个跨平台的直接操作excel原生格式的C++类库xlslib,http://sourceforge.net/projects/xlslib/正在研究,估计这才是我想要的

如何在Qt中使用xlslib,http://developer.qt.nokia.com/forums/viewthread/747,关键是没有msvc2005/2008如何才能编译得到需要的dll 或者.a库,这是问题

//////////////////////////////////////////////////////////////////////////

下面是QAxObject方法的代码备忘记录

在pro文件中增加

CONFIG +=axcontainer

LIBS +=-lqaxserver \

      -lqaxcontainer

 

在cpp文件中

#include <QAxObject>

       

    QAxObject *excel = NULL;
    QAxObject *workbooks = NULL;
    QAxObject *workbook = NULL;
    QAxObject *cell=NULL;
    excel = new QAxObject("Excel.Application");
    if (excel->isNull()) {//网络中很多使用excel==NULL判断,是错误的
        QMessageBox::critical(0, "错误信息", "没有找到EXCEL应用程序");
        return;
    }
    excel->dynamicCall("SetVisible(bool)", false);
    workbooks = excel->querySubObject("WorkBooks");
    workbook = workbooks->querySubObject("Open(QString,QVariant,QVariant)", fileName,3,true);//两个参数时,三个参数true和false都很正常,false 锁定excel文件,其它程序只能只读方式打开,否则程序正在处理excel文件时,在外面打开excel,程序异常退出
    if (!workbook) {
        QMessageBox::critical(0, "错误信息", "excel 文件不存在");
        return;
    }
    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();
    int intColStart = usedrange->property("Column").toInt();
    int intCols = columns->property("Count").toInt();
    int intRows = rows->property("Count").toInt();
 
    for(int i=intRowstsrt;i <intRowStart + intRows;i++){
for(j=intColStart ;j<intColStrt+intCols;j++){
       
        cell = worksheet->querySubObject("Cells(int,int)", i,j ); //获取单元格
        if(cell->property("Value").type()==QVariant::Double){
qDebug()<<QString::number(cell->property("Value").toDouble(),'f',0);
           
        }else if(cell->property("Value").type()==QVariant::QString){
qDebug()<<cell->property("Value").toString();
}
        
       
    }
    workbook->dynamicCall("Close (Boolean)", false);
    excel->dynamicCall("Quit (void)");
    delete workbook;
    delete workbooks;
    delete excel;
 
使用Activex读取excel速度不快,上千行的记录需要考虑用别的方法了,网上有直接读取excel格式文件的c++封装类,据说很快,没有下载测试

 

原创粉丝点击