//生成保存 Excel 文件的默认路径 QString MainWidget::getDefaultFilePath() const { QString basePath = pathEdit->text(); if (basePath.isEmpty() || !QDir(basePath).exists()) { basePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); } return QDir(basePath).filePath(QString("Data_%1.xlsx").arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss"))); }导出的文件后缀自动加(1)(2)等等

QString MainWidget::getDefaultFilePath() const {
QString basePath = pathEdit->text();
if (basePath.isEmpty() || !QDir(basePath).exists()) {
basePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
}
QDateTime currentDateTime = QDateTime::currentDateTime();
QString baseFileName = QString("Data_%1").arg(currentDateTime.toString("yyyyMMdd_HHmmss"));
QString fileName = baseFileName;
int count = 1;
// 检查文件是否存在,如果存在则添加序号
while (QFile::exists(QDir(basePath).filePath(fileName + ".xlsx"))) {
fileName = QString("%1(%2)").arg(baseFileName).arg(count++);
}
return QDir(basePath).filePath(fileName + ".xlsx");
}
修改说明:
-
生成基础文件名:
- 使用当前日期时间生成基础文件名,格式为
Data_YYYYMMDD_HHMMSS
。
- 使用当前日期时间生成基础文件名,格式为
-
检查文件是否存在:
- 如果文件已存在,则在基础文件名后添加序号
(1)
,(2)
等,直到找到一个未被使用的文件名。
- 如果文件已存在,则在基础文件名后添加序号
-
返回完整路径:
- 返回带有唯一文件名的完整路径。
通过这种修改,每次导出文件时,系统会自动检查目标路径下是否已有同名文件。如果有,则在文件名后添加序号,确保文件名唯一,避免覆盖已有文件。