最近做一个项目需要用Qt写一个上位机,实现从串口读取数据并将数据保存到Excel表格中,需要用到QAxObject这个类,但是qApplication=new QAxObject() 会报错,于是在 .pro文件中加入CONFIG += qaxcontainer,于是错误消除。
接着程序实现
- 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->dynamicCall("SetVisible (bool Visible)","false");
- excel->setProperty("DisplayAlerts", false);
-
- 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);
- QAxObject *cellX,*cellY;
- for(int i=0;i<curRow;i++){
- QString X="A"+QString::number(i+1);
- 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(ui->tableWidget->formula(i,0).toInt()));
- cellY->dynamicCall("SetValue(const QVariant&)",QVariant(ui->tableWidget->formula(i,1).toInt()));
- }
-
- workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filepath));
- workbook->dynamicCall("Close()");
- excel->dynamicCall("Quit()");
- delete excel;
- excel=NULL;
- }
另外附上在网上搜到的一些常用操作:
QAxWidget excel("Excel.Application");
1) 显示当前窗口:
excel.setProperty("Visible", true);
2) 更改 Excel 标题栏:
excel.setProperty("Caption", "Invoke Microsoft Excel");
3) 添加新工作簿:
QAxObject * workbooks = excel.querySubObject("WorkBooks");
workbooks->dynamicCall("Add");
4) 打开已存在的工作簿:
workbooks->dynamicCall("Open (const QString&)", QString("c:/test.xls"));
5) 获取活动工作簿:
QAxObject * workbook = excel.querySubObject("ActiveWorkBook");
6) 获取所有的工作表:
QAxObject * worksheets = workbook->querySubObject("WorkSheets");
7) 获取工作表数量:
int intCount = worksheets->property("Count").toInt();
8) 获取第一个工作表:
QAxObject * worksheet = workbook->querySubObject("Worksheets(int)", 1);
9) 获取cell的值:
QAxObject * range = worksheet->querySubObject("Cells(int,int)", 1, 1 );
以上操作不一定每个都可用(都好用),仅作为参考吧。起码我第9)个就没成功,不知为何?后来我改用了Range(QVariant, QVariant)的方法来替代它。