Simple implementation of CSV file import. Successfully imported items are appended to the model.

This commit is contained in:
2026-01-04 13:38:54 +01:00
parent 2ccbe3839a
commit 2702b9c835
10 changed files with 258 additions and 13 deletions

View File

@ -5,6 +5,8 @@
#include <QJsonDocument>
#include <QStandardPaths>
#include "../formats/csvparser.h"
bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName) {
qDebug() << "saving file...";
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
@ -29,25 +31,55 @@ bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName)
}
QByteArray FileHandler::loadJSONDataFromFile(const QString fileName) {
QByteArray jsonData;
QFile file;
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
file.setFileName(path + "/" + fileName);
QPair<QString, QByteArray> fileContent = getFileContent(path + "/" + fileName);
return fileContent.second;
}
QList<QHash<int, QVariant>> FileHandler::getItemValuesFromCSVFile(const QString& filePath) {
QList<QHash<int, QVariant>> result;
QFile file;
file.setFileName(filePath);
if (file.exists()) {
result = CsvParser::getItemsFromCSVFile(filePath);
}
return result;
}
FileHandler::FileHandler() {}
/** Tries to open the file specified by the file path & returns the content
* @brief FileHandler::getFileContent
* @param filePath
* @return Returns an error string (empty if successful) and the file content
*/
QPair<QString, QByteArray> FileHandler::getFileContent(const QString& filePath) {
QString errorString = "";
QByteArray fileContent;
QFile file;
file.setFileName(filePath);
if (file.exists()) {
qDebug() << "File found, reading content...";
const bool successfulOpened = file.open(QIODevice::ReadOnly | QIODevice::Text);
if (successfulOpened) {
// TODO learn and decide on the differences between "readAll" and using
// streams
jsonData = file.readAll();
fileContent = file.readAll();
file.close();
} else {
qWarning() << "File could not be opened!";
errorString = "File could not be opened!";
qWarning() << errorString;
}
} else {
qInfo() << "File not found. Returning empty result...";
errorString = "File not found. Returning empty result...";
qInfo() << errorString;
}
return jsonData;
}
FileHandler::FileHandler() {}
const QPair<QString, QByteArray> result(errorString, fileContent);
return result;
}