How to write CSV file in Qt?

  • Hi,

    how to write data from specific row in CSV file. i want write some data for (2column 1row) . how to write? any sample code or url pls.


  • @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( |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 (|QFile::Truncate))
    QTextStream stream(&file);
    stream << value1 << "\t" << value2 << "\n"; // this writes first line with two columns

  • Or, you use LibQxt's "QxtCsvModel": 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 << 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() <<",");
        return 0;

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.