#include<QApplication>
#include<QSqlDatabase>
#include<QDebug>
#include<QMessageBox>
#include<QSqlQuery>
#include<QVariant>
#include<QTime>
#include<QTextCodec>
voidwriteexcel (QStringexcelfilepath)
{
Creating a DB instance, setting the connection string
Qsqldatabasedb=qsqldatabase:: Adddatabase ("Qodbc", "Excelexport");
QStringdsn=QString("Driver={microsoft Excel DRIVER (*.xls)};D sn="; Firstrowhasnames=1; Readonly=false; Create_db=\ "%1\";D bq=%2 ").
Arg (Excelfilepath). Arg (Excelfilepath);
Db.setdatabasename (DSN);
Open Database
If(!db.open ())
{
Qdebug () <<"open false";
qmessagebox:: About (NULL,"R","open false");
}
Create a table
QStringsql="CREATE table sheet (name TEXT, age number)";
Qsqlqueryquery (db);
If(!query.exec (SQL))
{
Qdebug () <<"CREATE TABLE false! ";
qmessagebox:: About (NULL,"R","CREATE TABLE false! ");
}
Write Data
Db.exec ("INSERT into sheet (name, age) VALUES (' CTB ', '" ')');
Db.exec ("INSERT into sheet (name, age) VALUES (' XW ', 'n ')");
Db.exec ("INSERT into sheet (name, age) VALUES (' LG ', '" ') ');
Close the database
Db.close ();
}
voidreadexcel (constQStringexcelpath)
{
Excel database connection string requires QODBC driver
Qsqldatabasedb=qsqldatabase:: Adddatabase ("Qodbc"," Excelexport ");
QStringconnstring=QString("Driver={microsoft Excel Driver (*.xls)}; Readonly=1;driverid=790;dbq=%1;defaultdir=d:\\ "). Arg (Excelpath);
Db.setdatabasename (connstring);
Open Database
If(!db.open ())
{
Qdebug () <<"open false";
qmessagebox:: About (NULL,"R","open false");
}
Querying data
QStringsql="select * from [sheet$]";
Qsqlqueryquery (SQL,db);
while (Query.next ()){
Reading data
QStringname=query.value (0). toString ();
intage=query.value (1). ToInt ();
Qdebug () <<name<<age<<endl;
}
Close the database
Db.close ();
}
intmain (intargc,char*argv[])
{
QapplicationA (argc,argv);
Chinese support
qtextcodec:: Setcodecforlocale (qtextcodec:: Codecforname ("System"));
qtextcodec:: Setcodecfortr (qtextcodec:: Codecforname ("System"));
qtextcodec:: Setcodecforcstrings (qtextcodec:: Codecforname ("System"));
Writeexcel ("D:\\test01.xls");
Readexcel ("D:\\test01.xls");
returna.exec ();
}
Write Result: