QT打开一个路径下的所有的.xls文件,判断文件里面是否含有字符串“shijain”,并将所在的位置信息显示在textbrowe
时间: 2024-03-27 15:35:42 浏览: 103
QT选择打开指定目录文件,处理txt内容,并通过串口发送
可以使用Qt的QDir类来遍历指定路径下的所有.xls文件,然后使用QAxObject类打开Excel文件并查找字符串。以下是代码示例:
```cpp
QDir dir("your/path");
QStringList filters;
filters << "*.xls";
QFileInfoList fileList = dir.entryInfoList(filters);
foreach (QFileInfo file, fileList) {
QAxObject *excel = new QAxObject("Excel.Application");
QAxObject *workbooks = excel->querySubObject("Workbooks");
QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", file.absoluteFilePath());
QAxObject *worksheets = workbook->querySubObject("Worksheets");
int sheetCount = worksheets->property("Count").toInt();
for (int i = 1; i <= sheetCount; i++) {
QAxObject *sheet = worksheets->querySubObject("Item(int)", i);
QAxObject *usedRange = sheet->querySubObject("UsedRange");
QAxObject *find = usedRange->querySubObject("Find(QString)", "shijian");
if (find) {
int row = find->property("Row").toInt();
int column = find->property("Column").toInt();
QString info = QString("%1\t%2\t%3\n").arg(file.absoluteFilePath()).arg(i).arg(QString("%1,%2").arg(row).arg(column));
ui->textBrowser->append(info);
find->dynamicCall("Clear()");
delete find;
}
delete usedRange;
delete sheet;
}
workbook->dynamicCall("Close()");
delete workbook;
delete worksheets;
delete workbooks;
excel->dynamicCall("Quit()");
delete excel;
}
```
该代码会打开指定路径下的所有.xls文件,遍历文件中的所有工作表并查找是否包含字符串“shijian”,如果找到了,则会将文件路径、工作表序号以及字符串位置信息显示在textBrowser中。注意:需要在.pro文件中添加`LIBS += -lOleAut32`才能使用QAxObject类。
阅读全文