Qt实现将qsqlite数据库中的数据导出为Excel表格
作者:小灰灰搞电子
这篇文章主要为大家详细介绍了如何通过Qt实现将qsqlite数据库中的数据导出为Excel表格,文中的示例代码简洁易懂,有需要的小伙伴可以了解一下
1、首先添加库
QT += core gui sql axcontainer
sql:操作数据库
axcontainer:操作Excel表格
2、采用多线程的方式导出
expoer.h
#ifndef REPORTEXPORTTHREAD_H #define REPORTEXPORTTHREAD_H #include <QObject> #include <QDebug> #include <QThread> #include <QFile> #include <QFileInfo> #include <QAxObject> #include <QStandardPaths> #include <QDir> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QSqlRecord> #include <QThread> #include <QFileDialog> class ReportExportThread : public QObject { Q_OBJECT public: typedef enum { exporting, failed, finish, }ExportState; signals: void export_res_signal(ExportState state,QString info,quint32 totalNum,quint32 exportNum); public: explicit ReportExportThread(QObject *parent = nullptr); void export_thread_run(QString dbFile,QString dbTableName,QString xlsxFile); private: void castListListVariant2Variant(const QList<QList<QVariant> > &cells, QVariant &res); private: QAxObject *excel = nullptr;//excel操作对象 QAxObject *workbooks = nullptr; QAxObject* workbook = nullptr; //打开 QAxObject *activeWorkBook = nullptr; QAxObject *worksheet = nullptr; //表单 }; #endif // REPORTEXPORTTHREAD_H
export.cpp
#include "reportExportThread.h" #include "Windows.h" ReportExportThread::ReportExportThread(QObject *parent) : QObject{parent} { } void ReportExportThread::export_thread_run(QString dbFile, QString dbTableName, QString xlsxFile) { #define SINGLE_OPT_ROW 1000 QVariant var; QVariantList varList; QList<QVariant> listVar; QList<QList<QVariant> > listListVar; quint32 writeRowCnt = 1;//写入起始行计数 QString range; QString cmd; QAxObject *writeRange = nullptr; quint32 row,col; //数据库操作数据 QSqlDatabase *db = nullptr; QSqlDatabase dbA; QSqlQuery *query = nullptr; QString dbConnectName = "export"; QAxObject* cellInterior = nullptr; QAxObject *font = nullptr; QColor bkColor(255, 255, 0 ,50); quint32 i,j; #define asset_null(a,info)\ {\ if(a == nullptr)\ {\ emit export_res_signal(failed,info,0,0);\ goto EXIT;\ }\ }\ qDebug()<<"export_thread_run "<<QThread::currentThreadId(); //判断数据库文件是否存在 QFile dbFiles(dbFile); if(!dbFiles.exists()) { emit export_res_signal(failed,tr("数据库文件不存在!"),0,0); return; } dbFiles.close(); //判断表是否存在 if(dbTableName.isEmpty()) { emit export_res_signal(failed,tr("数据库表不存在!"),0,0); return; } //判断xlsx文件是否存在 QFile xlsxFiles(xlsxFile); if(!xlsxFiles.exists()) { if(!xlsxFiles.open(QIODevice::WriteOnly)) { emit export_res_signal(failed,tr("xlsx文件创建失败!"),0,0); return; } xlsxFiles.close(); } xlsxFiles.close(); //判断文件是否为只读 QFileInfo fileInfo(xlsxFile); fileInfo.setFile(fileInfo.filePath()+"/~$"+fileInfo.fileName()); if(fileInfo.exists()) //判断一下,有没有"~$XXX.xlsx"文件存在,是不是为只读 { emit export_res_signal(failed,tr("xlsx文件为只读文件!"),0,0); return; } fileInfo.setFile(xlsxFile); //创建QAxObject对象 CoInitializeEx(NULL, COINIT_MULTITHREADED); this->excel = new QAxObject();//建立excel操作对象 connect(excel,&QAxObject::exception,this, [](int code, const QString &source, const QString &desc, const QString &help) { qDebug()<<code; qDebug()<<source; qDebug()<<desc; qDebug()<<help; }); this->excel->setControl("Excel.Application");//连接Excel控件 this->excel->setProperty("Visible", false);//显示窗体看效果 this->excel->setProperty("DisplayAlerts", false);//显示警告看效果 this->excel->setProperty("Caption", "Qt Excel"); //标题为Qt Excel this->workbooks = excel->querySubObject("WorkBooks"); this->workbook = workbooks->querySubObject("Open(const QString&)",QDir::toNativeSeparators(fileInfo.absoluteFilePath())); //打开 this->activeWorkBook = excel->querySubObject("ActiveWorkBook"); this->worksheet = activeWorkBook->querySubObject("Sheets(int)",1); //获取表单 //创建QSqlDatabase对象 // dbA = QSqlDatabase::addDatabase("QSQLITE",dbConnectName); // dbA.setDatabaseName("sqltest.db"); db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE",dbConnectName)); // db->addDatabase("QSQLITE",dbConnectName); db->setDatabaseName(dbFile); //打开数据库 // if(!dbA.open()) // { // emit export_res_signal(failed,tr("数据库打开失败!"),0,0); // goto EXIT; // } // db = &dbA; if(!db->open()) { emit export_res_signal(failed,tr("数据库打开失败!"),0,0); goto EXIT; } query = new QSqlQuery(*db); //开始设置表头 cmd =QString("PRAGMA table_info(%1);").arg(dbTableName); if(!query->exec(cmd)) { emit export_res_signal(failed,tr("数据库表头操作失败!"),0,0); goto EXIT; } col = query->record().count(); //获取列数 listVar.clear(); listListVar.clear(); while(query->next()) { listVar.append(QVariant(query->value(1).toString())); //qDebug()<<query->value(1).toString(); } listListVar.append(listVar); this->castListListVariant2Variant(listListVar,var); range = QString("A1:%1%2").arg(QChar('A'+col-1)).arg(writeRowCnt++); //qDebug()<<range; writeRange = this->worksheet->querySubObject("Range(const QString&)",range); asset_null(writeRange,tr("Excel打开失败!")); writeRange->dynamicCall("Value", var); //开始设置表头背景颜色 cellInterior = writeRange->querySubObject("Interior"); asset_null(cellInterior,tr("Excel打开失败!")); cellInterior->setProperty("Color", bkColor); //开始调整背景字体 font = writeRange->querySubObject("Font"); //获取单元格字体 asset_null(font,tr("Excel打开失败!")); font->setProperty("Bold", true); //字体加粗 font->setProperty("Color", QColor(255, 0, 0)); //设置单元格字体颜色(红色) delete writeRange; //获取数据行数 cmd =QString("SELECT count(*) FROM %1;").arg(dbTableName); if(!query->exec(cmd)) { emit export_res_signal(failed,tr("数据库行数获取失败!"),0,0); goto EXIT; } query->next(); row = query->value(0).toInt(); //开始导出数据 for(i =0;i < row; i+=SINGLE_OPT_ROW) { listListVar.clear(); query->clear(); cmd =QString("select * from %1 limit %2,%3").arg(dbTableName).arg(i).arg(SINGLE_OPT_ROW); //qDebug()<<cmd; if(!query->exec(cmd)) { emit export_res_signal(failed,tr("数据库数据获取失败!"),0,0); goto EXIT; } //读取数据 int dataRowCnt = 0; while(query->next()) { listVar.clear(); for(j=0;j<col;j++) { listVar.append(query->value(j)); } listListVar.append(listVar); dataRowCnt++; } //写入数据 this->castListListVariant2Variant(listListVar,var); range = QString("A%1:%2%3").arg(writeRowCnt).arg(QChar('A'+col-1)).arg(dataRowCnt+writeRowCnt-1); //qDebug()<<range; writeRange = this->worksheet->querySubObject("Range(const QString&)",range); asset_null(writeRange,tr("Excel打开失败!")); writeRange->dynamicCall("Value", var); writeRowCnt+=dataRowCnt; delete writeRange; emit export_res_signal(exporting,tr("数据正在导出!"),row,writeRowCnt-2); } emit export_res_signal(finish,tr("数据导出成功!"),row,row); EXIT: if(this->excel != nullptr) { this->workbook->dynamicCall("Save()" ); this->workbook->dynamicCall("Close()"); //关闭文件 this->excel->dynamicCall("Quit()");//关闭excel delete excel; excel = nullptr; } if(query != nullptr) { delete query; query = nullptr; } if(db->isOpen()) { db->close(); delete db; QSqlDatabase::removeDatabase(dbConnectName); } } void ReportExportThread::castListListVariant2Variant(const QList<QList<QVariant> > &cells, QVariant &res) { QVariantList vars; const int rows = cells.size(); for(int i=0;i<rows;++i) { vars.append(QVariant(cells[i])); } res = QVariant(vars); }
3、如何使用
reportExportThread->start(); QString savePath = QFileDialog::getExistingDirectory(this,"请选择导入的文件夹!", "", QFileDialog::ShowDirsOnly); emit start_export_thread("sqltest.db","produceTable",savePath+"/"+QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss")+".xlsx");
4、结果查看
到此这篇关于Qt实现将qsqlite数据库中的数据导出为Excel表格的文章就介绍到这了,更多相关Qt数据库数据导出为Excel内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!