刚学QT的菜鸟,无聊的时候总会找一点事情做。言归正传,将excel表格保存到数据库,是比较简单的。我的想法简单粗暴:从路径中获取文件,通过按键控制加载。将大象放进冰箱需要是三步,
这个同样:1、获取路径
2、读取Excel文件
3、将其保存到数据库
获取路径我是通过类QFileDialog实现的,具体代码如下:
void form_tab::on_scanButton_clicked()
{
QFileDialog *fileDialog=new QFileDialog();
fileDialog->setFileMode(QFileDialog::ExistingFile);
fileDialog->setNameFilter(_T("CSV(*.csv)"));
QString openPath=QCoreApplication::applicationDirPath();
fileDialog->setDirectory(openPath);
if(fileDialog->exec()==QDialog::Accepted)
{
QString srcFile=fileDialog->selectedFiles()[0];
ui->lineEdit->setText(srcFile);
}
}
读excel文件和保存到数据库是同时进行的,可以说读取一条,保存一条。注意,excel文件都是在格式(.csv)下进行的。
void form_tab::on_addButton_clicked()
{
QString srcPath=ui->lineEdit->text();
if(srcPath.isEmpty())
{
QMessageBox::warning(0,tr("Path warning"),tr("Path is wrong"));
return;
}
QFile file(srcPath);
if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
{
std::cerr<<"Cannot open file for reading"
<<qPrintable(file.errorString())<<std::endl;
}
QSqlQuery query;
QStringList list;
list.clear();
QTextStream in(&file);
while(!in.atEnd())
{
QString fileLine=in.readLine(); //从第一行读取至下一行
list=fileLine.split(",",QString::SkipEmptyParts);
query.prepare("INSERT INTO _excel(id,tabid,profession,name,std_ID)"
"VALUES(:id,:tabid,:profession,:name,:std_ID)");
query.bindValue(":id",list.at(0));
query.bindValue(":tabid",_tabid);
query.bindValue(":profession",list.at(1));
query.bindValue(":name",list.at(2));
query.bindValue(":std_ID",list.at(3));
query.exec();
}
}
在这个基础上,为了方便查看,也就是看到效果,我用了两个表格视图QTableView进行显示。为什么是成对出现的呢,因为我喜欢成双成对?当然不是,为了一个显示加载的表格名字及信息,另一个显示表格的内容。在这个过程中不可避免的用到了表格模型:QSqlTableModel,QSqlRelationalTableModel,区别就是后者有外键,就跟两个小孩似的,性格差异,一个较为活泼,能够和别人联系起来,其他都是一样的。
//加载
void form_tab::on_addButton_clicked()
{
QString srcPath=ui->lineEdit->text();
if(srcPath.isEmpty())
{
QMessageBox::warning(0,tr("Path warning"),tr("Path is wrong"));
return;
}
QFile file(srcPath);
QFileInfo info=QFileInfo(srcPath);
QString filename=info.baseName();//studentUTF8
if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
{
std::cerr<<"Cannot open file for reading"
<<qPrintable(file.errorString())<<std::endl;
}
QDateTime dateTime= QDateTime::currentDateTime();
QString currentDT=dateTime.toString(_T("yyyy年MM月dd日 hh:mm:ss "));
QSqlQuery query;
query.exec(QString("SELECT MAX(%2)FROM%1").arg(" _excel").arg("tabid"));
query.next();
if(query.value(0).isNull())
{
qDebug()<<"query.value(0) is null";
}
int _tabid=query.value(0).toInt()+1;
qDebug()<<_tabid<<endl;
query.exec("insert into tableInfo values(NULL,'"+filename+"','"+currentDT+"')");
tableInfoModel=new QSqlTableModel(this);
tableInfoModel->setTable("tableInfo");
// tableInfoModel->setSort(2,Qt::AscendingOrder);
tableInfoModel->setHeaderData(1,Qt::Horizontal,tr("Name"));
tableInfoModel->setHeaderData(2,Qt::Horizontal,tr("Date"));
tableInfoModel->select();
ui->tableView->setModel(tableInfoModel);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setItemDelegate(new QSqlRelationalDelegate(this));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setColumnHidden(0,true); //隐藏id
ui->tableView->resizeColumnsToContents();
ui->tableView->horizontalHeader()->setStretchLastSection(true);
// ui->tableView->setCurrentIndex(tableInfoModel->index(0,2));
QStringList list;
list.clear();
QTextStream in(&file);
while(!in.atEnd())
{
QString fileLine=in.readLine(); //从第一行读取至下一行
list=fileLine.split(",",QString::SkipEmptyParts);
query.prepare("INSERT INTO _excel(id,tabid,profession,name,std_ID)"
"VALUES(:id,:tabid,:profession,:name,:std_ID)");
query.bindValue(":id",list.at(0));
query.bindValue(":tabid",_tabid);
query.bindValue(":profession",list.at(1));
query.bindValue(":name",list.at(2));
query.bindValue(":std_ID",list.at(3));
query.exec();
}
excelModel=new QSqlRelationalTableModel(this);
excelModel->setTable("_excel");
excelModel->setRelation(Tab_EX_Id,QSqlRelation("tableInfo","id","name"));
excelModel->setHeaderData(Ex_Id,Qt::Horizontal,_T("序号"));
excelModel->setHeaderData(Ex_Profession,Qt::Horizontal,_T("专业"));
excelModel->setHeaderData(Ex_Name,Qt::Horizontal,_T("名字"));
excelModel->setHeaderData(Ex_StuId,Qt::Horizontal,_T("学号"));
excelModel->select();
ui->excelView->setModel(excelModel);
// ui->excelView->setItemDelegate(new QSqlRelationalDelegate(ui->excelView)); //委托
ui->excelView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->excelView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->excelView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->excelView->horizontalHeader()->setStretchLastSection(true);
ui->excelView->setColumnHidden(Tab_EX_Id,true);
updateExcelView();
}
updateExcelView()函数就是更新视图,将两者同步起来。敌不动,我不动。
void form_tab::updateExcelView()
{
QModelIndex index=ui->tableView->currentIndex();
// qDebug()<<"row="<<index.row();
if(index.isValid())
{
QSqlRecord record=tableInfoModel->record(index.row());
int id=record.value("id").toInt();
// qDebug()<<"id="<<id;
excelModel->setFilter(QString("tabid=%1").arg(id));
// excelModel->setFilter(QString("tabid=1"));
excelModel->select();
}
excelModel->select();
ui->excelView->horizontalHeader()->setVisible(excelModel->rowCount()>0);
}
最终效果:(原谅我是个女生)