SoFunction
Updated on 2025-04-18

QT performs CSV file initialization and read and write operations

Preface

The reason why the csv file is recommended by users is that it can be opened in Excel, and it can also be opened in a text editor. The text content is also displayed in a regular manner, and users can clearly see it when viewed. So it is actually explained here. The operation of csv is actually that you usually use txt file operations. It is just that we save text according to the format of csv (xxx, xxx columns and columns are directly separated by English commas), and at the same time, we modify the suffix name of the text to csv. Next, we will have a detailed understanding of the reading and writing operations.

1. CSV file initialization

If our local drive letter does not exist, we usually create a csv file first, and look at the program below, so click directly.

    // Let's put it in the C://CSV folder    QString strDir = QString("%1/%2").arg("C://").arg("CSV");
    
    // Check if there is a folder, let the program create a folder first    QDir dirCSV;
    if (!(strDir))
        (strDir);

    // Use the time format to name the csv file    m_strFilePath = strDir + "/" + QString("csv%").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    
    // Because it is a file operation, it is safer to add a lock    static QMutex mutex;
    ();
    QFile fileCSV;
    
    // Determine whether the file does not exist    if (!(m_strFilePath))
    {
        QFile file(m_strFilePath);
        if ((QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            QTextStream in(&file);
            QString strText("");
            // The file does not exist. The first time we will write a list name for it, so that it will be clearer when viewing the csv file when it is opened.            strText = QString("DateTime,") + QString("Info");
            in << strText << '\n';
            ();
        }
    }
    ();

2. CSV writing

The writing method is actually just to write according to the format we defined before, and the main file is just to open, and is it the same for reading? I won't go into details here.

    static QMutex mutex;
    ();
    QFile file(m_strFilePath);
    if ((QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        QString strCurTime = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        QTextStream in(&file);
        QString strMessage = QString(u8"%1,%2").arg(strCurTime).arg(strText);

        in << strMessage << '\n';
        ();
    }

    ();

3. CSV reading

    static QMutex mutex;
        ();
        QFile file(m_strFilePath);
        if ((QIODevice::ReadOnly))
        {
            QTextStream out(&file);
            QStringList tempOption = ().split("\n");
            for (int i = 0; i < (); i++)
            {
                float fArea = 0;
                QStringList tempbar = (i).split(",");
                ();   // last is empty item

                if (() > 0)
                {
                    if ((0).indexOf(QString("DateTime")) != -1)
                        continue;

                    m_StrAlarmInfoList << tempOption[i];
                }
            }
        }

        ();
        ();

4. QT reads the csv file line by line

QT reads the csv file line by line and divides the data on each line. Note: The csv file is actually a text file, and each line of data can be divided by commas or tab characters. Between reading csv files, it is best to change the csv suffix to txt and see if the separator is a comma or a tab character. The sample code is as follows:

#include &lt;QtCore/QCoreApplication&gt;
#include &lt;QDir&gt;
#include &lt;QFile&gt;
#include &lt;QFileInfo&gt;
#include &lt;QDebug&gt;
#include &lt;QTextCodec&gt;
#include &lt;QDateTime&gt;
#include &lt;&gt;


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

	QString exeDir = qApp-&gt;applicationDirPath();
	QString csvFile = ("/custom_test.csv");
	csvFile = QDir::toNativeSeparators(csvFile);

	//Read the file	QFile file(csvFile);
	bool bopen = (QIODevice::ReadOnly | QIODevice::Text);
	if (!bopen) 
	{
		qDebug() &lt;&lt; "failed to open file.";
	}
	else
	{
		DWORD dwStart = ::GetTickCount();

		//Put csv data line by line to buff		QVector&lt;QStringList&gt; buff;

		// Read files in text stream mode		QTextStream in(&amp;file);
		while (!()) {
			QString strline = ();
			if (()) {
				continue;
			}
			//
			QStringList _lst = ("\t");
			(_lst);

			QString newLine = "";
			for (int i = 0; i &lt; _lst.length(); i++)
			{
				QString item = _lst[i];
				(item);
				("$");
			}
			qDebug() &lt;&lt; "newLine=" &lt;&lt; newLine;
		}

		DWORD dwTake = ::GetTickCount() - dwStart;
		qDebug() &lt;&lt; "take time=" &lt;&lt; dwTake;
	}
	();

    return ();
}

5. How to save data into CSV file

It is very convenient to open and save csv files in Qt. It is easy to operate directly in the form of ordinary text. It is still very simple to use QTextStream to read and write standardized.

Specific examples:

void mainwindow::OnExportBtnClicked()
{
    //1.Select the exported csv file saving path    QString csvFile = QFileDialog::getExistingDirectory(this);
    if(())
       return;
    
    //2. The file name uses the system timestamp to generate a unique file    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy_MM_dd_hh_mm_ss");
    csvFile += tr("/%1_DTUConfigInfo_export_%").arg(username).arg(current_date);
    
    //3. Open the .csv file with QFile. If it does not exist, a new file will be automatically created.    QFile file(csvFile);
    if ( ())
    {
        //If the file exists and executes the operation, it is empty because the file cannot exist    }
    ( QIODevice::ReadWrite | QIODevice::Text );
    statusBar()-&gt;showMessage(tr("Exporting data...."));
    QTextStream out(&amp;file);
    
    //4. Get the data Create the first line    out&lt;&lt;tr("UID,")&lt;&lt;tr("sysID,")&lt;&lt;tr("UsrID,")&lt;&lt;tr("MeterNum,")&lt;&lt;tr("CMD,\n");//Table header    //Other data can be added in this way 
    //5. The file needs to be closed after writing the data    ();
}
 

This is the article about QT CSV file initialization and read and write operations. For more related QT CSV file content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!