首页 > 代码库 > QOdbc 读写 excel
QOdbc 读写 excel
#include <QApplication>#include <QSqlDatabase>#include <QDebug>#include <QMessageBox>#include <QSqlQuery>#include <QVariant>#include <QTime>#include <QTextCodec>void writeExcel(QString excelFilePath){// 创建一个数据库实例, 设置连接字符串QSqlDatabase db = QSqlDatabase::addDatabase("QODBC","excelexport");QString dsn = QString("DRIVER={Microsoft Excel Driver (*.xls)};DSN=‘‘; FIRSTROWHASNAMES=1; READONLY=FALSE;CREATE_DB=\"%1\";DBQ=%2").arg(excelFilePath).arg(excelFilePath);
db.setDatabaseName(dsn);
// 打开数据库if (!db.open()){
qDebug()<< "open false";QMessageBox::about(NULL, "r", "open false");}
// 创建表格QString sql = "create table sheet (name TEXT, age NUMBER)";QSqlQuery query(db);if (!query.exec(sql)){
qDebug()<< "create table false!";QMessageBox::about(NULL, "r", "create table false!");}
// 写入数据db.exec( "insert into sheet(name, age) values(‘ctb‘, ‘28‘)");db.exec( "insert into sheet(name, age) values(‘xw‘, ‘19‘)");db.exec( "insert into sheet(name, age) values(‘lg‘, ‘34‘)");// 关闭数据库db.close();
}void readExcel(const QString excelPath){// excel 数据库连接字符串 须要QODBC 驱动QSqlDatabase db = QSqlDatabase::addDatabase("QODBC","excelexport");QString connString = QString("Driver={Microsoft Excel Driver (*.xls)};Readonly=1;DriverId=790;Dbq=%1;DefaultDir=D:\\").arg(excelPath);db.setDatabaseName(connString);
// 打开数据库if (!db.open()){
qDebug()<< "open false";QMessageBox::about(NULL, "r", "open false");}
//查询数据QString sql = "Select * from [sheet$]";QSqlQuery query(sql, db);while (query.next()) {//读取数据QString name = query.value(0).toString();int age = query.value(1).toInt();qDebug()<< name << age <<endl;}
// 关闭数据库db.close();
}int main(int argc, char *argv[]){QApplication a(argc, argv);//中文支持QTextCodec::setCodecForLocale(QTextCodec::codecForName("system"));QTextCodec::setCodecForTr(QTextCodec::codecForName("system"));QTextCodec::setCodecForCStrings(QTextCodec::codecForName("system"));writeExcel("D:\\test01.xls");readExcel("D:\\test01.xls");return a.exec();}写入结果:
读取打印结果:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。