Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create .csv file in C++ in qt

I want to create an csv file using c++, using Qt for application and UI framework. Is there's library for csv file.

like image 967
Kamesh Avatar asked Apr 02 '14 05:04

Kamesh


Video Answer


3 Answers

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.

like image 183
iamantony Avatar answered Oct 18 '22 02:10

iamantony


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);
like image 1
lpapp Avatar answered Oct 18 '22 02:10

lpapp


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.

like image 1
rioki Avatar answered Oct 18 '22 03:10

rioki