Qt使用QXlsx将Excel表格数据导入到SQLite数据库
这是我记录Qt学习过程的第8篇心得文章,上次写到Qt使用QAxObject将Excel表格数据导入到SQLite数据库,使用过程中发现,执行效率不高,于是就研究了QXlsx,发现利用QXlsx处理Excel真的太方便了,上一篇写了使用QXlsx将QTableView数据导出到Excel表格,肯定少不了数据导入的啊,上代码。
实现代码:
//读取EXcel数据导入到SQLite数据库,使用QXlsx
bool Skysonya::readExcelToSQLiteByQXlsx(const QString &fileName, QSqlDatabase sqliteDB, QString tableName,
QString strTitle)
{
QXlsx::Document xlsx(fileName);
if (!xlsx.load())
{
messageBox("critical", strTitle, "打开Excel文件失败!");
return false;
}
int rowCount = xlsx.dimension().rowCount();
int colCount = xlsx.dimension().columnCount();
QSqlQuery query(sqliteDB);
query.exec("select * from " + tableName);
QSqlRecord emptyRec = query.record(); //获取空记录,只有字段名
QStringList fieldList{};
for (int i = 1; i < emptyRec.count(); i++)
{
fieldList.append(emptyRec.fieldName(i));
}
QString sql = fieldList.join(",");
qDebug() << strTitle + "SQL:" << sql << Qt::endl;
sql = "insert into " + tableName + " (" + sql + ") values ";
qDebug() << strTitle + "SQL:" << sql << Qt::endl;
fieldList.clear();
// 遍历单元格
for (int row = 2; row < rowCount + 1; row++)
{
QStringList fList{};
for (int col = 2; col < colCount + 1; col++)
{
// 获取单元格
fList.append("'" + xlsx.read(row, col).toString() + "'");
}
fieldList.append("(" + fList.join(",") + ")");
qDebug() << strTitle + "SQL:"
<< "(" + fList.join(",") + ")" << Qt::endl;
}
sql += fieldList.join(",");
// qDebug() << strTitle + "SQL:" << sql << Qt::endl;
// 创建一个Warning弹出对话框,添加按钮:"Yes"、"No"、"Cancel"
QString strInfo = "替换请选\"是\",追加请选\"否\",取消请选\"取消\"!";
QMessageBox *msgBox = new QMessageBox(QMessageBox::Warning, strTitle, strInfo,
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
msgBox->button(QMessageBox::Yes)->setText("是"); //将"Yes"按钮改为显示"是"
msgBox->button(QMessageBox::No)->setText("否"); //将"No"按钮改为显示"否"
msgBox->button(QMessageBox::Cancel)->setText("取消"); //将"Cancel"按钮改为显示"取消"
int result = msgBox->exec(); //显示Warning弹出对话框
switch (result)
{
case QMessageBox::Yes:
query.clear();
query.exec("delete from " + tableName);
query.clear();
query.exec("delete from sqlite_sequence where name = '" + tableName + "'");
strInfo = strTitle + ":数据替换";
break;
case QMessageBox::No:
strInfo = strTitle + ":数据追加";
break;
default:
break;
}
query.clear();
if (!query.exec(sql))
{
messageBox("critical", strTitle, strInfo + "失败\n" + query.lastError().text());
qDebug() << strInfo + "失败:" << query.lastError() << Qt::endl;
return false;
}
qDebug() << strInfo + "成功!" << Qt::endl;
xlsx.deleteLater();
return true;
}
messageBox()函数参考拙文QT实现QMessageBox中文按钮
QXlsx下载与配置,查阅QXlsx Qt操作excel,作者周不易,在此也表示感谢!