• Qt 写Excel


    bool ExcelIO::saveFromTable(DataTable *table, QString tablename, QString filePath)
    {
        if (filePath.isEmpty() || tablename.isEmpty()){
            emit signal_SaveAsSuccess(false);
            return false;
        }
        //把"test.xlsx"中//替换为所在系统分隔符,否则路径读取会失败
        filePath = QDir::toNativeSeparators(filePath);
        HRESULT result = OleInitialize(nullptr); 
        if (result != S_OK && result != S_FALSE)
        {
            qDebug()<<QString("Could not initialize OLE (error %x)").arg(static_cast<unsigned int>(result));
        }
    
        QAxObject *excel = new QAxObject(this);
    
        excel->setControl("Excel.Application");
    
    //    excel->dynamicCall("SetVisible(bool Visible)","false");
        excel->setProperty("DisplayAlerts", true);
        QAxObject *workBooks = excel->querySubObject("WorkBooks");
        workBooks->dynamicCall("Add");
    
        QAxObject *workBook = excel->querySubObject("ActiveWorkBook");
        QAxObject *workSheets = workBook->querySubObject("WorkSheets");
    
        QAxObject *workSheet = workSheets->querySubObject("Item(int)",1);
        workSheet->setProperty("Name",tablename);
        int column = table->columnCount();
        int row = table->rowCount();
        for (int k = 0; k < column; k++)
        {
            QString header = table->getHorHeader()->getEnglishNameByIndex(k);
            QAxObject *range = workSheet->querySubObject("Cells(int,int)",1,k+1);
            range->dynamicCall("Value",header);
        }
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
            {
                QString tableitem = table->getItemData(i, j).toString();
                QAxObject *range = workSheet->querySubObject("Cells(int,int)",i+2,j+1);
                range->dynamicCall("Value",tableitem);
            }
        }
    
        workBook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filePath));
        workBook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");
        delete excel;
        excel = nullptr;
    
        emit signal_SaveAsSuccess(true);
        return true;
    }
  • 相关阅读:
    Render Props
    react16新特性
    typescript
    calc
    类数组
    promise fullfill状态时 value是一个promise,那么此promise.then()里面收到的是什么
    M个同样的苹果放N个同样的盘子,允许有盘子空着, 问有多少种放法?
    history
    js创建二维数组
    钉钉-E应用开发初体验(企业内部应用)
  • 原文地址:https://www.cnblogs.com/azbane/p/12121690.html
Copyright © 2020-2023  润新知