之前替学校考试科用C++ Builder做过一个小的数据库工具,处理excel表格用的,现在想转换到Qt平台下来,在网上搜了搜有一些利用OBDC读取xls文件的教程:
http://hi.baidu.com/kxw102/item/770c496d5736470ca0cf0f1d
http://blog.sina.com.cn/s/blog_55758bcf0100d4lm.html
试了一下可以用,但是转换到图形界面中遇到点问题,在用QSqlTableModel类的setTable()方法使无法读取到[Sheet1$]表格,将其换为QsqlQueryModel后问题解决。代码如下:
头文件mainWindow.h:
#ifndef mainWindow_H #define mainWindow_H#include <QWidget> #include <QTextEdit> #include <QSqlQueryModel>class QSqlTableModel; class QTableView;enum {Id = 0,Eat = 1,Taxi = 2,Train = 3 };class mainWindow : public QWidget {Q_OBJECTpublic:mainWindow();bool createConnection();void createFakeData();void printMessage(QString message);private:QSqlQueryModel *model;QTableView *view;QTextEdit *textEdit;};#endif
类定义文件mainWindow.cpp:
#include <QtGui> #include <QtSql>#include "mainWindow.h"mainWindow::mainWindow() {textEdit=new QTextEdit();if (!createConnection())return;model = new QSqlTableModel(this);model->setQuery("SELECT * FROM [Test$]");model->setHeaderData(Eat, Qt::Horizontal, tr("Eat"));model->setHeaderData(Taxi, Qt::Horizontal, tr("Taxi"));model->setHeaderData(Train, Qt::Horizontal, tr("Train"));view = new QTableView;view->setModel(model);view->setSelectionMode(QAbstractItemView::SingleSelection);view->setSelectionBehavior(QAbstractItemView::SelectRows);view->setColumnHidden(Id, false);view->resizeColumnsToContents();view->setEditTriggers(QAbstractItemView::NoEditTriggers);QHeaderView *header = view->horizontalHeader();header->setStretchLastSection(true);QVBoxLayout *mainLayout = new QVBoxLayout;mainLayout->addWidget(view);mainLayout->addWidget(textEdit);setLayout(mainLayout);setWindowTitle(tr("xlsProcessor")); }bool mainWindow::createConnection() {QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");db.setDatabaseName("Driver={Microsoft Excel Driver (*.xls)};Readonly=0;DriverId=790;Dbq=D:\\test.xls;DefaultDir=D:\\");if (!db.open()){printMessage(tr("Database Error"));return false;}printMessage(tr("Connected Successed!"));return true; }void mainWindow::printMessage(QString message) {textEdit->append(message); }
最终效果: