89 lines
2.2 KiB
C++
89 lines
2.2 KiB
C++
|
|
#include "ConfigFiles.h"
|
|||
|
|
#include <QFile>
|
|||
|
|
#include <QDebug>
|
|||
|
|
ConfigFiles::ConfigFiles(QObject *parent) : QObject(parent)
|
|||
|
|
{
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* @brief ReadFile_Csv 读取 CSV 文件,返回行列表
|
|||
|
|
* @param &filePath CSV 文件路径
|
|||
|
|
* @return QList<QStringList> 每个 QStringList 为一行的字段
|
|||
|
|
*/
|
|||
|
|
QList<QStringList> ConfigFiles::ReadFile_Csv(const QString &filePath){
|
|||
|
|
QList<QStringList> rows;
|
|||
|
|
|
|||
|
|
QFile file(filePath);
|
|||
|
|
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
|
|||
|
|
{
|
|||
|
|
qWarning() << "CSV 打开失败:" << file.errorString();
|
|||
|
|
return rows;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
QTextStream in(&file);
|
|||
|
|
//in.setCodec("UTF-8"); // 如有需要可改成 "GBK"
|
|||
|
|
|
|||
|
|
QStringList currentRow;
|
|||
|
|
QString currentField;
|
|||
|
|
bool inQuote = false;
|
|||
|
|
|
|||
|
|
while (!in.atEnd())
|
|||
|
|
{
|
|||
|
|
QString line = in.readLine();
|
|||
|
|
|
|||
|
|
// 处理跨行引号:如果上一行未闭合,继续拼
|
|||
|
|
if (inQuote)
|
|||
|
|
currentField += "\n";
|
|||
|
|
else
|
|||
|
|
currentField.clear();
|
|||
|
|
|
|||
|
|
for (int i = 0; i < line.size(); ++i)
|
|||
|
|
{
|
|||
|
|
QChar ch = line.at(i);
|
|||
|
|
|
|||
|
|
if (ch == '\"')
|
|||
|
|
{
|
|||
|
|
// 连续两个引号表示转义
|
|||
|
|
if (i + 1 < line.size() && line.at(i + 1) == '\"')
|
|||
|
|
{
|
|||
|
|
currentField += '\"';
|
|||
|
|
++i; // 跳过下一个引号
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
inQuote = !inQuote;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
else if (ch == ',' && !inQuote)
|
|||
|
|
{
|
|||
|
|
// 字段结束
|
|||
|
|
currentRow << currentField.trimmed();
|
|||
|
|
currentField.clear();
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
currentField += ch;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 如果引号已闭合,把最后一列也加入并结束本行
|
|||
|
|
if (!inQuote)
|
|||
|
|
{
|
|||
|
|
currentRow << currentField.trimmed();
|
|||
|
|
rows << currentRow;
|
|||
|
|
currentRow.clear();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 如果文件结尾时引号未闭合,把剩余部分作为最后一列
|
|||
|
|
if (!currentField.isEmpty() || !currentRow.isEmpty())
|
|||
|
|
{
|
|||
|
|
currentRow << currentField.trimmed();
|
|||
|
|
rows << currentRow;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
file.close();
|
|||
|
|
return rows;
|
|||
|
|
}
|