咔片PPT · AI自动生成演示文稿,模板丰富、排版精美 讯飞智文 · 一键生成PPT和Word,高效应对学习与办公

Qt不仅可读取Word中的文本,还能对存有大量信息的表格数据进行读取和查询。本文实例完整地演示对Word中表格遍历、读取指定行和列信息的通行方式。

1.数据准备

事先准备好“1977-2019历年全国高考人数和录取率统计.docx”数据表,存放在“D:Temp”下待用,如下图所示。

2.程序界面

创建Qt桌面应用程序项目,项目名称为“WordReadTable”。设计程序界面,数据检索程序界面如图所示。

3.全局变量及方法

“mainwindow.h”头文件的代码如下:

#include #include class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_btnQuery_clicked(); private: Ui::MainWindow *ui; QAxObject *myword; //Word应用程序指针 QAxObject *mydocs; //文档集指针 QAxObject *document; //文档指针 QAxObject *mytable; //文档中的表指针 };

4.功能实现

实现具体功能的代码皆在“mainwindow.cpp”源文件中,如下:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); myword = new QAxObject("Word.Application"); //创建 Word 应用程序对象 mydocs = myword->querySubObject ("Documents"); //获取文档集 mydocs->dynamicCall("Open(const QString&)", "D:\Temp\1977-2019历年全国高考人数和录取率统计.docx"); //打开文档 document = myword->querySubObject("ActiveDocument"); //当前活动文档 mytable = document->querySubObject("Tables(int)", 1); //第一张表 int rows = mytable->querySubObject("Rows")->dynamicCall("Count").toInt(); //获取表格总行数 for(int i=2; iquerySubObject("Cell(int,int)",i,1); //读取第一列年份信息 if(headcol == NULL) continue; QString yearStr = headcol->querySubObject("Range")->property("Text").toString(); ui->comboYear->addItem(yearStr); //载入界面上的年份列表 if(i==rows) ui->comboYear->setCurrentText(yearStr); //默认显示最近年份(2019) } } MainWindow::~MainWindow() { delete ui; delete mytable; mytable=nullptr; document->dynamicCall("Close()"); myword->dynamicCall("Quit()"); } void MainWindow::on_btnQuery_clicked() { int rows = mytable->querySubObject("Rows")->dynamicCall("Count").toInt(); for(int i=2; iquerySubObject("Cell(int,int)",i,1); if (headcol == NULL) continue; QString yearStr = headcol->querySubObject("Range")->property("Text").toString(); if(ui->comboYear->currentText()==yearStr){ //以年份为关键字检索 QAxObject *infocol = mytable->querySubObject("Cell(int,int)", i, 2); QString totalStr = infocol->querySubObject ("Range")->property("Text").toString(); //读取当年高考人数 ui->edtTotal->setText(totalStr); infocol = mytable->querySubObject("Cell(int,int)", i, 3); QString admitStr = infocol->querySubObject("Range")->property("Text").toString(); //读取录取人数 ui->edtAdmit->setText(admitStr); infocol = mytable->querySubObject("Cell(int,int)", i, 4); QString rateStr = infocol->querySubObject("Range")->property("Text").toString(); //读取录取率 ui->edtRate->setText(rateStr); break; } } }

上面的程序完整地演示了对Word中表格遍历、读取指定行和列信息的通行方式,请务必熟练掌握。

5.运行效果

运行程序,从下拉列表中选择年份后,单击“查询”按钮,程序会在Word文档的表格中读取该年高考生总人数、录取人数和录取率数据,并显示在界面上对应的栏里,如下图所示。

————————————————

觉得有用的话请关注点赞,谢谢您的支持!

对于本系列文章相关示例完整代码有需要的朋友,可关注并在评论区留言!