函数声明部分:需求:将tableview中显示的数据导出到Excel表格中
首先在项目文件.pro中加入
QT += axcontainer
同时在操作的界面上加入头文件#include<QAxObject>,采用Excel控件
tableview是利用QSqlTableModel调用的数据库,若不想显示某列数据,调用hideCloumn(),在打印的时候判断isColumnHidden()隐藏的列跳过即可,,主要实现代码如下:
//隐藏列
ui->tableView->hideColumn(0);
//判断隐藏列
if(tableView->isColumnHidden(j))
声明部分:
//将数据保存为excel
bool static save(QString filePath,QStringList headers,QList<QStringList> data,QString comment="");
//将QTableView保存为excel
bool static saveFromTable(QString filePath,QTableView *tableView,QString comment="");
bool static insert(QSqlQuery& query, QString sheetName, QStringList slist);
实现部分:
bool UIDemo01::saveFromTable(QString filePath, QTableView *tableView, QString comment)
{
QAbstractItemModel *model=tableView->model();
const int column=model->columnCount();
const int row=model->rowCount();
//header
QStringList headers;
for(int i=0;i<column;i++)
{
//隐藏列
if(tableView->isColumnHidden(i))
continue;
headers<<model->headerData(i,Qt::Horizontal).toString();
}
//data
QStringList list;
QList<QStringList> data;
for(int i=0;i<row;i++)
{
if(model->index(i,0).data().isNull())
continue;
list.clear();
for(int j=0;j<column;j++){
//隐藏列
if(tableView->isColumnHidden(j))
continue;
list<<model->index(i,j).data().toString();
}
data<<list;
}
return UIDemo01::save(filePath,headers,data,comment);
}
bool UIDemo01::save(QString filePath, QStringList headers, QList<QStringList> data,QString comment)
{
QString sheetName = "Sheet1";
// 创建一个数据库实例, 设置连接字符串
QSqlDatabase dbexcel = QSqlDatabase::addDatabase("QODBC","excelexport");
if(!dbexcel.isValid())
{
qDebug()<<"数据库驱动异常";
return false; //! type error
}
QString dsn = QString("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%1\";DBQ=%2").
arg(filePath).arg(filePath);
qDebug()<<dsn;
dbexcel.setDatabaseName(dsn);
// open connection
if(!dbexcel.open())
{
qDebug()<<"无法打开数据库";
return false; //! db error
}
QSqlQuery query(dbexcel);
QString sql;
// drop the table if it's already exists
sql = QString("DROP TABLE [%1]").arg(sheetName);
query.exec( sql);
//create the table (sheet in Excel file)
sql = QString("CREATE TABLE [%1] (").arg(sheetName);
foreach (QString name, headers) {
sql +=QString("[%1] varchar(200)").arg(name);
if(name!=headers.last())
sql +=",";
}
sql += ")";
query.prepare(sql);
if( !query.exec()) {
//UIDemo01::printError( query.lastError());
dbexcel.close();
return false;
}
foreach (QStringList slist, data) {
insert(query,sheetName,slist);
}
if(!comment.isEmpty())
{
QStringList slist;
slist<<comment;
for(int i=0,n=headers.size()-1;i<n;i++)
{
slist<<"";
}
insert(query,sheetName,slist);
}
dbexcel.close();
return true;
}
bool UIDemo01::insert(QSqlQuery &query, QString sheetName, QStringList slist)
{
QString sSql = QString("INSERT INTO [%1] VALUES(").arg(sheetName);
for(int i=0,n=slist.size();i<n;i++)
{
sSql+=QString(":%1").arg(i);
if(i!=n-1)
sSql+=",";
else
sSql+=")";
}
query.prepare(sSql);
for(int i=0,n=slist.size();i<n;i++)
{
query.bindValue(QString(":%1").arg(i),slist.at(i));
}
if( !query.exec()) {
return false;
}
return true;
}
调用代码:
void UIDemo01::on_pushButtonOutExcel_clicked()
{
QFileDialog dlg;
QString filename;
dlg.setAcceptMode(QFileDialog::AcceptSave);
// Qt 5
dlg.setDirectory(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
// Qt 4
// dlg.setDirectory(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
dlg.setNameFilter("*.xls");
filename=QDate::currentDate().toString("yyyy-MM-dd")+"body.xls";
dlg.selectFile(filename);
if(dlg.exec()!= QDialog::Accepted)
return;
QString filePath=dlg.selectedFiles()[0];//得到用户选择的文件名
qDebug()<<filePath;
if(UIDemo01::saveFromTable(filePath,ui->tableViewCheck,"注释:无")) {
QMessageBox::information(this,tr("提示"),tr("保存成功"));
}
else{
QMessageBox::information(this,tr("提示"),tr("保存失败"));
}
}
有一点需要注意的是,在调用Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)注意中间有空格