How to write CSV file in Qt?
-
@QString filename = QFileDialog::getSaveFileName(this, "DialogTitle", "filename.csv", "CSV files (.csv);;Zip files (.zip, *.7z)", 0, 0); // getting the filename (full path)
QFile data(filename);
if(data.open(QFile::WriteOnly |QFile::Truncate))
{
QTextStream output(&data);
output << "'your csv content';'more csv content'"
}
@
that's the way i do it -
You write CSV files like any other text file with QTextStream.
@
double value1(10);
double value2(13.2);
QFile file("./file.csv");
if (file.open(QFile::WriteOnly|QFile::Truncate))
{
QTextStream stream(&file);
stream << value1 << "\t" << value2 << "\n"; // this writes first line with two columns
(...)
file.close();
}@ -
Or, you use LibQxt's "QxtCsvModel":http://libqxt.bitbucket.org/doc/0.6/qxtcsvmodel.html class. It provides an [[doc:QAbstractItemModel]] type interface for CSV files.
-
Try qtcsv library for reading and writing csv-files. I tried to make it small and easy-to-use. See Readme file for library documentation and code examples.
Quick Example:
#include <QList> #include <QStringList> #include <QDir> #include <QDebug> #include "qtcsv/stringdata.h" #include "qtcsv/reader.h" #include "qtcsv/writer.h" int main() { // prepare data that you want to save to csv-file QStringList strList; strList << "one" << "two" << "three"; QtCSV::StringData strData; strData.addRow(strList); strData.addEmptyRow(); strData << strList << "this is the last row"; // write to file QString filePath = QDir::currentPath() + "/test.csv"; QtCSV::Writer::write(filePath, strData); // read data from file QList<QStringList> readData = QtCSV::Reader::readToList(filePath); for ( int i = 0; i < readData.size(); ++i ) { qDebug() << readData.at(i).join(","); } return 0; }