您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

QOdbc读写excel

2024/3/7 1:06:44发布11次查看
#include qapplication #include qsqldatabase #include qdebug #include qmessagebox #include qsqlquery #include qvariant #include qtime #include qtextcodec void writeexcel(qstring excelfilepath) { // 创建一个数据库实例, 设置连接字符串 qsqlda
#include
#include
#include
#include
#include
#include
#include
#include
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 < }



// 关闭数据库

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


写入结果:
读取打印结果
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product