Example code:
#include <QtCore/QCoreApplication>
#include <QtSql>
#include <QObject>
#include <qdebug.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
if(!db.isValid())
{
qDebug() << "Type Error!";
return 0;
}
/*
* Excel 2003
*db.setDatabaseName("Driver={Microsoft Excel Driver (*.xls)};Readonly=0;DriverId=790;Dbq=d:\\temp\\book1.xls;DefaultDir=d:\\temp");
*/
/*
*Excel 2007及以上
*/
QString connString = QString("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%1")
.arg("D:\\ProgramProject\\ODBC_Excel\\ODBC_Excel\\data.xlsx");
db.setDatabaseName(connString);
/*
*其他操作与数据库的操作是一样的
*/
if ( db.open())
{
qDebug() << "Open Excel Successful!";
QSqlQuery query(db);
query.exec("select name,age from [sheet1$]");
while (query.next())
{
QString strName = query.value(0).toString();
QString strAge = query.value(1).toString();
qDebug() << strName << strAge;
}
}
else
qDebug() << db.lastError().text();
/*
*善后操作
*/
db.close();
db.removeDatabase(connString);
return 0;
//return a.exec();//不进入事件循环,直接结束程序
}
1, Consider an Excel file (for example, Book.xls) as a database in which each worksheet (sheet) is considered a database table. Assume that the first behavior field name in Excel, so you must include the contents of the first row in the scope that you define.
< Span style= "FONT-SIZE:14PX; Font-family:simsun; line-height:21px; " >2, the name of the table must be added $ and the square brackets on both sides ( insert a row of data, Standard SQL statement, table name must be in [Excel file name $] format, reading data from Excel tables, standard SQL statements, table names must be in [table name $] Format
query exec ( "CREATE TABLE Guest (visitor text,age int,comments text)" //this is the action to create the table
query exec ( "INSERT into [sheet1$] values (1, ' Ane Brun ', 7)" //this is the action inserted
From for notes (Wiz)
QT uses ODBC to manipulate Excel