亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

QT進(jìn)行CSV文件初始化與讀寫操作

 更新時(shí)間:2025年04月18日 10:40:28   作者:進(jìn)擊的大海賊  
這篇文章主要為大家詳細(xì)介紹了在QT環(huán)境中如何進(jìn)行CSV文件的初始化、寫入和讀取操作,本文為大家整理了相關(guān)的操作的多種方法,希望對大家有所幫助

前言

csv文件之所以被用戶推薦使用,我覺得即可以用excel打開,同時(shí)也是可以用文本編輯器打開,而且文本內(nèi)容的顯示也是比較有規(guī)律,用戶查看起來也是能清晰看的明白,所以這里其實(shí)就是已經(jīng)講得出來了,csv的操作,其實(shí)就是你平時(shí)使用txt文件操作,只是我們按照csv的格式(xxx,xxx 列與列直接用英文逗號分開)進(jìn)行文本保存,同時(shí)將文本的后綴名修改成csv罷了,接下來我們就進(jìn)行讀寫的操作具體的了解。

一、CSV文件初始化

那如果我們本地盤符就是不存在csv文件,通常我們都是會先創(chuàng)建一個(gè)csv文件,看下下面的程序吧,這樣直接點(diǎn)。

    // 我們都放C://CSV文件夾里面吧
    QString strDir = QString("%1/%2").arg("C://").arg("CSV");
    
    // 先檢查有沒有文件夾存在,沒有就讓程序創(chuàng)建文件夾先
    QDir dirCSV;
    if (!dirCSV.exists(strDir))
        dirCSV.mkpath(strDir);

    // 使用時(shí)間格式進(jìn)行csv文件命名吧
    m_strFilePath = strDir + "/" + QString("csv%1.csv").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    
    // 因?yàn)槭俏募僮?,安全一些都是加個(gè)鎖
    static QMutex mutex;
    mutex.lock();
    QFile fileCSV;
    
    // 判斷文件是否不存在
    if (!fileCSV.exists(m_strFilePath))
    {
        QFile file(m_strFilePath);
        if (file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            QTextStream in(&file);
            QString strText("");
            // 文件不存在,第一次,我們就給他寫個(gè)列表名字,這樣csv文件打開時(shí)候查看的時(shí)候就比較清晰
            strText = QString("DateTime,") + QString("Info");
            in << strText << '\n';
            file.close();
        }
    }
    mutex.unlock();

二、CSV寫入

寫入的方式其實(shí)就是按照我們之前定義的格式寫入就行了,主要文件打開的方式就行了,讀取的也是一樣嗎,這里不做贅述。

    static QMutex mutex;
    mutex.lock();
    QFile file(m_strFilePath);
    if (file.open(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';
        file.close();
    }

    mutex.unlock();

三、CSV讀取

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

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

                    m_StrAlarmInfoList << tempOption[i];
                }
            }
        }

        file.close();
        mutex.unlock();

四、QT 逐行讀取csv文件

QT逐行讀取csv文件,并對每行的數(shù)據(jù)進(jìn)行分割。注意:csv文件其實(shí)就是文本文件,每行數(shù)據(jù)可以用逗號或者制表符進(jìn)行分割。在讀取csv文件之間,最好是把csv后綴改為txt,看一下分隔符到底是逗號還是制表符。示例代碼如下:

#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include <QTextCodec>
#include <QDateTime>
#include <windows.h>


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

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

	//讀取文件
	QFile file(csvFile);
	bool bopen = file.open(QIODevice::ReadOnly | QIODevice::Text);
	if (!bopen) 
	{
		qDebug() << "failed to open file.";
	}
	else
	{
		DWORD dwStart = ::GetTickCount();

		//將csv數(shù)據(jù)逐行讀取放置到buff
		QVector<QStringList> buff;

		// 文本流模式讀取文件
		QTextStream in(&file);
		while (!in.atEnd()) {
			QString strline = in.readLine();
			if (strline.isEmpty()) {
				continue;
			}
			//
			QStringList _lst = strline.split("\t");
			buff.append(_lst);

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

		DWORD dwTake = ::GetTickCount() - dwStart;
		qDebug() << "take time=" << dwTake;
	}
	file.close();

    return a.exec();
}

五、Qt如何將數(shù)據(jù)保存成CSV文件

在Qt中打開與保存csv文件十分方便,直接按照普通文本的形式操作,用QTextStream進(jìn)行標(biāo)準(zhǔn)化的讀寫,還是很簡單。

具體例如:

void mainwindow::OnExportBtnClicked()
{
    //1.選擇導(dǎo)出的csv文件保存路徑
    QString csvFile = QFileDialog::getExistingDirectory(this);
    if(csvFile.isEmpty())
       return;
    
    //2.文件名采用系統(tǒng)時(shí)間戳生成唯一的文件
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy_MM_dd_hh_mm_ss");
    csvFile += tr("/%1_DTUConfigInfo_export_%2.csv").arg(username).arg(current_date);
    
    //3.用QFile打開.csv文件 如果不存在則會自動(dòng)新建一個(gè)新的文件
    QFile file(csvFile);
    if ( file.exists())
    {
        //如果文件存在執(zhí)行的操作,此處為空,因?yàn)槲募豢赡艽嬖?
    }
    file.open( QIODevice::ReadWrite | QIODevice::Text );
    statusBar()->showMessage(tr("正在導(dǎo)出數(shù)據(jù)。。。。。。"));
    QTextStream out(&file);
    
    //4.獲取數(shù)據(jù) 創(chuàng)建第一行
    out<<tr("UID,")<<tr("sysID,")<<tr("UsrID,")<<tr("MeterNum,")<<tr("CMD,\n");//表頭
    //其他數(shù)據(jù)可按照這種方式進(jìn)行添加即可
 
    //5.寫完數(shù)據(jù)需要關(guān)閉文件
    file.close();
}
 

到此這篇關(guān)于QT進(jìn)行CSV文件初始化與讀寫操作的文章就介紹到這了,更多相關(guān)QT CSV文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論