- 粗略操作
QT += core gui sql
CONFIG += qaxcontainer
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./sql/contact.db");
if(!db.open())
{
qDebug()<<"open sql failed !";
return;
}
model = new QSqlQueryModel(ui->tableview);
model->setQuery(QString("select * from phonebook;"));
model->setHeaderData(0,Qt::Horizontal,QObject::tr("Name"));
model->setHeaderData(1,Qt::Horizontal,QObject::tr("Tel"));
ui->tableview->setModel(model);
db.close();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString filepath=QFileDialog::getSaveFileName(this,tr("Save orbit"),".",tr("Microsoft Office 2007 (*.xlsx)"));//获取保存路径
if(!filepath.isEmpty()){
QAxObject *excel = new QAxObject(this);
excel->setControl("Excel.Application");//连接Excel控件
excel->dynamicCall("SetVisible (bool Visible)","false");//不显示窗体
excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改,是否保存”的提示
QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
workbooks->dynamicCall("Add");//新建一个工作簿
QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
QAxObject *worksheets = workbook->querySubObject("Sheets");//获取工作表集合
QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);//获取工作表集合的工作表1,即sheet1
QAxObject *cellX,*cellY;
for(int i=0;i<model->rowCount();i++){
QString X="A"+QString::number(i+1);//设置要操作的单元格,如A1
QString Y="B"+QString::number(i+1);
cellX = worksheet->querySubObject("Range(QVariant, QVariant)",X);//获取单元格
cellY = worksheet->querySubObject("Range(QVariant, QVariant)",Y);
cellX->dynamicCall("SetValue(const QVariant&)",QVariant(model->record(i).value("Name").toString()));//设置单元格的值
cellY->dynamicCall("SetValue(const QVariant&)",QVariant(model->record(i).value("Tel").toString()));
}
workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filepath));//保存至filepath,注意一定要用QDir::toNativeSeparators将路径中的"/"转换为"\",不然一定保存不了。
workbook->dynamicCall("Close()");//关闭工作簿
excel->dynamicCall("Quit()");//关闭excel
delete excel;
excel=NULL;
}
}
http://www.heilqt.com/topic/56e90da0e498871267b374cf
时间: 2024-12-28 02:19:25