Qt 쓰기 Excel

6867 단어
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()<"Could not initialize OLE (error %x)").arg(static_castint>(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;
}

좋은 웹페이지 즐겨찾기