I want to create an csv file using c++, using Qt for application and UI framework. Is there's library for csv file.
Try qtcsv library for reading and writing csv-files. 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;
}
I tried to make it small and easy-to-use. See Readme file for library documentation and other code examples.
QStringList strList;
strList << "one" << "two" << "three" << "with,comma";
and got one,two,three,with,comma
in file instead of one,two,three,"with,comma"
, am I use it correctly or lib can't handle such simple thing? –
Boehmenism Just writing CSV? Although google may reveal some CSV libraries, the probable reason why you have not found any is because it is so darn trivial. Remember CSV is just Comma Separated Values.
To implement it use any means to write a text file (std::ofstream, QFile, QTextStream) and do something along the lines of:
foreach record
{
foreach value in record
{
write "\"" + escape(value) + "\""
if not last value in record
{
write ","
}
}
write "\n"
}
escape (value)
{
replace each "\"" with "\"\""
}
Note that you can write the values without quotes if they do not contain any separators (,). Also note you can use different separators, for example the semi-colon is commonly used.
escape
function, I dare say it's not so trivial :( –
Macknair write "\n"
is in the wrong spot, move it down a line –
Virgilvirgilia ,
, ;
, \t
) and escape sequences (""
, \"
), including the C-style escapes (\n
, \r
\t
, \a
, etc.) or newlines in within sting (which is allowed). Reading CSV is would always encourage to use a lib. –
Amnesty You could basically look into libqxt.
Using QxtCsvModel
The QxtCsvModel [libqxt.bitbucket.org] class provides a QAbstractTableModel [qt-project.org] for CSV Files. This is perhaps the easiest way possible to read and write csv files without having to parse the csv format to something qt can understand. It’s as simple as using one line of code, for example the following reads the csv file:
csvmodel->setSource(fileName);
© 2022 - 2024 — McMap. All rights reserved.