1. 程式人生 > 其它 >Qt QAxObject 批量寫入 Excel

Qt QAxObject 批量寫入 Excel

// 計算行的Range名稱
QString excelHCalc(int n) {
    QString h;
    while (n > 0) {
        h.prepend(static_cast<char>((n % 26) + 'A' - 1));
        n /= 26;
    }
    return h;
}

// 初始化
QAxObject *excel = new QAxObject();
QAxObject *workBooks = new QAxObject();
QAxObject *workBook = new QAxObject();
QAxObject 
*workSheets = new QAxObject(); QAxObject *workSheet = new QAxObject(); QAxObject *workRange; // 配置 if (excel->setControl("Excel.Application")) { // 使用office qDebug() << "使用Office"; } else if (excel->setControl("ket.Application")) { // 使用wps qDebug() << "使用WPS"; } else { qWaring()
<< "未安裝Office或WPS"; QMessageBox::warning(this, tr("錯誤"), tr("未安裝Office或WPS")); return; } excel->setProperty("Visible", true); // 設定為可見 workBooks = excel->querySubObject("WorkBooks"); // 操作表 workBooks->dynamicCall("Add"); // 新建 if (excel->setProperty("Caption", "Qt Excel")) { //
開啟為 Excel qDebug() << R"(Qt Excel)"; } else if (!excel->setProperty("Caption", "DataToExcel")) { // 使用wps qDebug() << R"(DataToExcel)"; } else { qWaring() << "錯誤的Caption"; QMessageBox::warning(this, tr("錯誤"), tr("錯誤的Caption")); return; } workBook = excel->querySubObject("ActiveWorkBook"); workSheets = workBook->querySubObject("Sheets"); workSheet = workSheets->querySubObject("Item(int)", 1); workSheet->setProperty("Name", "Data"); // 設定工作表名稱 // 資料 QVariantList table; // 表格 QVariantList tableLine; // 表格行 // 測試 for (int i = 0; i < 100; ++i) { // tableLine << QStringLiteral("test%1").arg(i); } for (int i = 0; i < 100; ++i) { // table << QVariant(tableLine); // 每次新增一行 } // 獲取最寬列寬 int maxLineLength = 0; int lineLength = 0; for (const auto &line : table) { lineLength = line.toList().size(); if (maxLineLength < lineLength) { maxLineLength = lineLength; } } // 一次性寫入 QString range = QStringLiteral("A1:%1%2").arg(excelHCalc(maxLineLength)).arg(table.size()); workRange = workSheet->querySubObject("Range(const QString&)", range); // workRange->setProperty("Value2", QVariant(table)); // 儲存 QString filePath = QString("./datas/export/"); QString fileName = QString("data_%1.xls").arg(QDateTime::currentDateTime().toString("yyyyMMddHHmmss")); QDir dir; if (!dir.exists(filePath)) { // 如果資料夾不存在 dir.mkpath(filePath); // 則建立資料夾 } workBook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(filePath + fileName)); // 儲存 // 關閉 //excel->dynamicCall("Quit(void)"); // 刪除 不然程序會進後臺不會自動關閉 delete workRange; workRange = Q_NULLPTR; delete workSheet; workSheet = Q_NULLPTR; delete workSheets; workSheets = Q_NULLPTR; delete workBook; workBook = Q_NULLPTR; delete workBooks; workBooks = Q_NULLPTR; delete excel; excel = Q_NULLPTR;

轉自:https://vanxkr.com/2020/12/Qt-Excel-write/