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; }