QT打开一个路径下的所有的.xls文件,并使用qdebug打印出打开的所有的文件的名字,判断文件里面是否含有字符串“shijain”,并将所在的位置信息显示在textbrowe
时间: 2024-03-27 07:39:41 浏览: 61
好的,以下是代码实现:
```cpp
#include <QDir>
#include <QFileInfoList>
#include <QTextStream>
#include <QMessageBox>
void MainWindow::openExcelFiles()
{
QString folderPath = "your/folder/path"; // 文件夹路径
QDir folder(folderPath);
QFileInfoList fileList = folder.entryInfoList(QStringList() << "*.xls" << "*.xlsx", QDir::Files);
// 获取文件夹下所有的xls和xlsx文件
foreach (QFileInfo file, fileList) {
if (file.isFile() && file.exists()) {
QString filePath = file.absoluteFilePath(); // 文件的绝对路径
QString fileName = file.fileName(); // 文件名
qDebug() << fileName;
if (containsStringInExcel(filePath, "shijian")) {
// 文件中包含字符串"shijian"
ui->textBrowser->append(fileName + ": " + filePath);
}
}
}
}
bool MainWindow::containsStringInExcel(const QString &filePath, const QString &searchString)
{
QAxObject excel("Excel.Application");
QAxObject *workbooks = excel.querySubObject("Workbooks");
QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", filePath);
QAxObject *worksheets = workbook->querySubObject("Worksheets");
int sheetCount = worksheets->property("Count").toInt();
for (int i = 1; i <= sheetCount; i++) {
QAxObject *worksheet = worksheets->querySubObject("Item(int)", i);
QAxObject *usedRange = worksheet->querySubObject("UsedRange");
QAxObject *rows = usedRange->querySubObject("Rows");
int rowCount = rows->property("Count").toInt();
QAxObject *columns = usedRange->querySubObject("Columns");
int columnCount = columns->property("Count").toInt();
for (int row = 1; row <= rowCount; row++) {
for (int column = 1; column <= columnCount; column++) {
QAxObject *cell = worksheet->querySubObject("Cells(int,int)", row, column);
QString cellText = cell->property("Value").toString();
if (cellText.contains(searchString, Qt::CaseInsensitive)) {
// 单元格中包含searchString
workbook->dynamicCall("Close()");
excel.dynamicCall("Quit()");
return true;
}
}
}
worksheet->dynamicCall("Release()");
usedRange->dynamicCall("Release()");
rows->dynamicCall("Release()");
columns->dynamicCall("Release()");
}
workbook->dynamicCall("Close()");
excel.dynamicCall("Quit()");
return false;
}
```
这段代码会遍历指定路径下所有的.xls和.xlsx文件,使用qDebug打印出所有打开的文件名,如果文件中包含字符串"shijian",则将文件名和位置信息显示在textBrowser中。
阅读全文