通过QT查找Word中的关键字,并做高亮或删除操作
最近由于项目需要,要用QT操作Word文档。具体的工作需求:在指定的Word文档(*.doc文件/*.docx文件)中查找关键字,找到后做高亮操作或者直接删除操作,然后另存为到别的目录(表示这个文件被操作过了)。
这个功能很简单,确实挺简单,但由于是第一次用QT操作Word文档,所以仍需要经过一番查找资料。网上用QT操作Word文档的资料不是很多(可能是我没找对地方),所以经过了一段时间的碰壁之后(没有现成的,哪怕是半成品),我决定还是从源头看起:
1.查看帮助文档:Microsoft Word Visual Basic参考.chm。这是操作Word文档的VBA接口文档
2.查看官方网站的帮助文档:https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word?view=word-pia
“查找”在这:https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.find.hithighlight?view=word-pia#Microsoft_Office_Interop_Word_Find_HitHighlight_System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__System_Object__
要想用QT操作office文档,就要用到QAxWidget类和QAxObject类首先要在pro文件中配置一个模块“qaxcontainer”,也就是添加一行代码,即:
CONFIG += qaxcontainer
在找到关键字之后,我还保存了一些数据:文件名、文件所在的路径、关键字所处的位置。如果你不需要这些数据,可以删减掉。
QList<QString> fileNameList; // 保存文件名
QList<QString> filePathList; // 保存文件路径
QList<QStringList> keyWordsPositionList; // 保存关键字所在位置
首先介绍一个函数,这个函数通过正则表达式用来定位关键字所处在的语句。这个函数会在后面的高亮操作函数和直接删除函数里调用到:
// 查找关键字的位置
// fileContent:文件内容;keyWord:关键字
QStringList findKeyWordsPosition(QString fileContent, QString keyWord)
{
QStringList resList;
if (fileContent.contains(keyWord)){
qDebug() << QObject::tr("包含子字符串 : %1").arg(keyWord); int startIndex = ;
// int count = 0;
int keyWordsLen = keyWord.length();
QRegExp rx(QObject::tr("[,。:\r]?([^,。:\r]*(%1)[^,。:\r]*)[,。:\r]?").arg(keyWord)); while ((startIndex = rx.indexIn(fileContent, startIndex)) != -){
QString resStr = rx.cap().mid(); // 提取子字符串所在的语句
if (resStr.contains("\r"))
resStr.replace("\r", "");
resList << resStr; // 找到子字符串
int findIndex = fileContent.indexOf(keyWord, startIndex);
// qDebug() << QObject::tr("keyWords 出现的位置 : %1").arg(findIndex);
startIndex = findIndex + keyWordsLen;
// qDebug() << QObject::tr("keyWords 出现的次数 : %1").arg(++count);
qDebug() << "\n";
} return resList;
}
return resList << "";
}
首先是高亮操作函数:
// 高亮操作函数
// dirName:是待检查文件的路径;keyWords:是要查找的关键字(查找的关键字可能是多个)
bool highLightKeyWordsinWordFile(QString dirName, QStringList keyWords)
{
int lastSeparatorIndex = dirName.lastIndexOf(QDir::separator());
QString saveAsFilePath = storeDir + dirName.mid(lastSeparatorIndex+); // 另存为的路径 QAxWidget wordApplication("Word.Application");
QAxObject *documents = wordApplication.querySubObject("Documents");
documents->dynamicCall("Open(const QString&)", dirName);
wordApplication.setProperty("Visible", QVariant(false));
QAxObject* m_doc = wordApplication.querySubObject("ActiveDocument"); // 获取当前工作簿
QAxObject* pRange = m_doc->querySubObject("Content()"); if (NULL != pRange)
{
// 查找关键字
QAxObject *pFind = pRange->querySubObject("Find()");
QStringList keyWordsPosition;
if (NULL != pFind)
{
pFind->dynamicCall("ClearFormatting()");
pFind->setProperty("Format", true);
pFind->setProperty("MatchCase", false);
pFind->setProperty("MatchWholeWord", false);
pFind->setProperty("MatchByte", true);
pFind->setProperty("MatchWildcards", false);
pFind->setProperty("MatchSoundsLike", false);
pFind->setProperty("MatchAllWordForms", false); for (int i=; i<keyWords.size(); ++i){
// 找到关键字所在的位置,得到一个position,将position添加到keyWordsPosition中。
QString keyWord = keyWords.at(i);
QStringList position = findKeyWordsPosition(pRange->property("Text").toString(), keyWord);
if (!position.contains("")){
keyWordsPosition << position; pFind->setProperty("Text", keyWord);
pFind->dynamicCall("Execute()");
while (pFind->property("Found").toBool())
{
bool isHighlight = pFind->parent()->setProperty("HighlightColorIndex","wdYellow");
pFind->dynamicCall("Execute()"); if (!isHighlight)
{
delete pFind;
pFind = NULL;
delete pRange;
pRange = NULL;
m_doc->dynamicCall("Close(boolean)", true);
wordApplication.dynamicCall("Quit ()");
delete m_doc;
m_doc = NULL;
return false;
}
}
}
}
}
if (keyWordsPosition.size() >= ){
QString fileName = dirName.mid(lastSeparatorIndex+);
QString filePath = dirName.mid(, lastSeparatorIndex+);
fileNameList << fileName;
filePathList << filePath;
keyWordsPositionList << keyWordsPosition; m_doc->dynamicCall("SaveAs(const QString)", saveAsFilePath);
}
delete pFind;
pFind = NULL;
delete pRange;
pRange = NULL;
m_doc->dynamicCall("Close(Boolean)", true);
m_doc->dynamicCall("Quit()");
delete m_doc;
m_doc = NULL;
return true;
}
return true;
}
下面这个是直接删除操作函数
// dirName:是待检查文件的路径;keyWords:是要查找的关键字(查找的关键字可能是多个)
bool directDeleteKeyWordsinWordFile(QString dirName, QStringList keyWords)
{
int lastSeparatorIndex = dirName.lastIndexOf(QDir::separator());
QString saveAsFilePath = storeDir + dirName.mid(lastSeparatorIndex+); // 另存为的路径 QAxWidget wordApplication("Word.Application");
QAxObject *documents = wordApplication.querySubObject("Documents");
documents->dynamicCall("Open(const QString&)", dirName);
wordApplication.setProperty("Visible", QVariant(false));
QAxObject* m_doc = wordApplication.querySubObject("ActiveDocument"); // 获取当前工作簿
QAxObject* pRange = m_doc->querySubObject("Content()");
QList<QVariant> vars; if (NULL != pRange)
{
// 查找关键字
QAxObject *pFind = pRange->querySubObject("Find()");
QStringList keyWordsPosition;
if (NULL != pFind)
{
pFind->dynamicCall("ClearFormatting()");
QAxObject *replacement = pFind->querySubObject("Replacement()");
replacement->dynamicCall("ClearFormatting()"); for (int i=; i<keyWords.size(); ++i){
QString keyWord = keyWords.at(i);
// 找到关键字所在的位置,得到一个position,将position添加到keyWordsPosition中。
QStringList position = findKeyWordsPosition(pRange->property("Text").toString(), keyWord);
if (!position.contains("")){
keyWordsPosition << position;
vars << keyWord << false << false << false << false
<< false << true << << false << ""
<< << false << false << false << false; // wdReplaceNone-->0;wdReplaceAll-->2;wdReplaceOne-->1
bool isReplaced = pFind->dynamicCall("Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, "
"MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, "
"Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)", vars).toBool();
if (!isReplaced){
delete pFind;
pFind = NULL;
delete pRange;
pRange = NULL;
m_doc->dynamicCall("Close(Boolean)", true);
m_doc->dynamicCall("Quit()");
delete m_doc;
m_doc = NULL;
QMessageBox openFileError(QMessageBox::Warning,
QObject::tr("文件处理错误"),
QObject::tr("文件 %1 处理错误,是否继续检查其他文件?").arg(dirName));
openFileError.addButton(QMessageBox::Yes);
openFileError.addButton(QMessageBox::No);
openFileError.setDefaultButton(QMessageBox::Yes);
if (openFileError.exec() == QMessageBox::No)
return false;
} }
}
}
if (keyWordsPosition.size() >= ){
QString fileName = dirName.mid(lastSeparatorIndex+);
QString filePath = dirName.mid(, lastSeparatorIndex+);
fileNameList << fileName;
filePathList << filePath;
keyWordsPositionList << keyWordsPosition; m_doc->dynamicCall("SaveAs(const QString)", saveAsFilePath);
}
delete pFind;
pFind = NULL;
delete pRange;
pRange = NULL;
m_doc->dynamicCall("Close(Boolean)", true);
m_doc->dynamicCall("Quit()");
delete m_doc;
m_doc = NULL;
return true;
}
return false;
}
好了,以上代码可能无法正常运行,因为缺少一些变量的定义、头文件的包含,我觉得这些你自己添加是完全OK的^-^。
因为自己需要的时候找不到资源,如果你也在找相似的资料,能给你带来帮助,我的目的就达到了,哈哈
我发现在网上下载Word VBA和Excel VBA帮助文档的时候需要金币什么的,很不方便。在此我还将Word VBA和Excel VBA帮助文档的百度网盘下载链接放在这里,供大家下载:
链接: https://pan.baidu.com/s/1-KTGdEVz_4C3yp_SBNlkIw 提取码: ri4p
有不足的地方,请指正。
通过QT查找Word中的关键字,并做高亮或删除操作的更多相关文章
- Word中的代码怎样语法高亮
在平常我们粘贴代码到Word中的时候,经常会遇到代码粘贴到Word中后没有语法高亮,看着很乱很不友好,Word自带的样式---语法使用着也不尽人意, 网上有很多做法可以使得在插入在Word中的代码能够 ...
- word中使用MathType能做什么
在Office中写论文,特别是一些比较专业的论文需要用到各种公式的.会发现有很多地方Office自带的公式编辑器都无法完成,所以要用到MathType公式编辑器这个好用的工具了.MathType是一款 ...
- MySQL查找数据中相同的数据,并进行删除
查找表中多余的重复记录,重复记录是根据某个字段来判断 select * from 表名 where 字段 in (select 字段 from 表名 group by 字段 having count( ...
- Qt 向word中插入文字(使用QAxWidget和QAxObject)
pro 文件中要加入 CONFIG += qaxcontainer 2. main.cpp #include <QApplication> #include <QAxWidget&g ...
- Qt树形控件QTreeView使用1——节点的添加删除操作 复选框的设置
QtreeView是ui中最常用的控件,Qt中QTreeWidget比QTreeView更简单,但没有QTreeView那么灵活(QTreeWidget封装的和MFC的CTreeCtrl很类似,没有m ...
- 在PHP中如何实现在做了么个操作后返回到指定页面
我们经常会碰到类似用户在没有登录的情况下进行提问.评论,需要用户登录后返回刚才浏览的网页,这种功能用cookie保存当前url地址来实现.我用的是jquery,读者需要懂点jquery中的ajax请求 ...
- [Word]中批量修改图片大小和缩放比例方法
最近小编遇到一个问题:需要将一篇厘米.打开.宏名起好了,单击"创建"进入.返回word,工具-宏-宏(或者直接按Alt+F8),再次进入宏的界面,选择刚才编辑好的宏,并单击&quo ...
- C# 在word中查找及替换文本
C# 在word中查找及替换文本 在处理word文档时,很多人都会用到查找和替换功能.尤其是在处理庞大的word文档的时候,Microsoft word的查找替换功能就变得尤为重要,它不仅能让我们轻易 ...
- 用matlab查找txt文档中的关键字,并把关键字后面的数据存到起来用matlab处理
用matlab查找txt文档中的关键字,并把关键字后面的数据存到起来用matlab处理 我测了一组数据存到txt文件中,是个WIFI信号强度文档,里面有我们需要得到的数据,有没用的数据,想用matla ...
随机推荐
- 40 final、finally、finalize的区别
1.final 用于声明属性.方法.类.分别表示属性不可被改变,方法不可被覆盖,类不可被继承. (1)一个类不能既被声明为abstract的,又被声明为final的. (2)被声明为final的变量必 ...
- layui 获取iframe层的window
success: function (layero, index) { var iframeWin = $("div.layui-layer-content > iframe" ...
- 【crontab】误删crontab及其恢复
中秋节快到了,首先祝自己中秋快乐. 昨天下午六点,心里正想着加完一个crontab就可以下班了.本来想执行 crontab -e的,没想到手一抖就输入了crontab ,然后就进入了下面这个样子.
- PHP基础教程探讨一些php编程性能优化总结
兄弟连PHP培训 小编最近在做php程序的性能优化,一些经过测试后发现的东西就先记录下来,以备后用. 首先对于一些反应慢的操作或页面要跟踪处理一下,可以使用webGrind的方式看一下主要问题出在 ...
- Java对数组和列表的排序1.8新特性
Java对数组列表的排序 数组 Integer[] a = new Integer[] { 1, 2, 3, 4, 5, 6, 9, 8, 7, 4, 5, 5, 6, 6 }; Arrays.sor ...
- CDOJ 1061 C - 秋实大哥与战争 STL set 迭代器
题目链接: C - 秋实大哥与战争 Time Limit:1000MS Memory Limit:65535KB 64bit IO Format:%lld & %llu Sub ...
- nginx展示文件目录
1. 如何让nginx显示文件夹目录 vi /etc/nginx/conf.d/default.conf 添加如下内容: location / { root /data/www/file //指定实际 ...
- Introduction-to-Psychology Slides
最近在网易公开课学习耶鲁大学Paul Bloom教授的<心理学导论>,英文水平有限,视频中一直没有出现PPT,无意中找到一份课件,现分享于此,大家自取! 链接:https://pan.ba ...
- springboot(一).初识springboot以及基本项目搭建
初识springboot 以及基本项目搭建 由于新的项目需要搭建后台框架,之前的springmvc架构也使用多次,在我印象中springboot的微服务架构更轻量级更容易搭建,所以想去试试spring ...
- 跨平台迁移数据库windows-Linux
将10.10.1.127服务器的数据库ORCL(WINDOWS)迁移到VM 10.10.10.168LINUX平台 操作系统:Windows server 2008r2 64bit CentOS L ...