QT進行CSV文件初始化與讀寫操作
前言
csv文件之所以被用戶推薦使用,我覺得即可以用excel打開,同時也是可以用文本編輯器打開,而且文本內(nèi)容的顯示也是比較有規(guī)律,用戶查看起來也是能清晰看的明白,所以這里其實就是已經(jīng)講得出來了,csv的操作,其實就是你平時使用txt文件操作,只是我們按照csv的格式(xxx,xxx 列與列直接用英文逗號分開)進行文本保存,同時將文本的后綴名修改成csv罷了,接下來我們就進行讀寫的操作具體的了解。
一、CSV文件初始化
那如果我們本地盤符就是不存在csv文件,通常我們都是會先創(chuàng)建一個csv文件,看下下面的程序吧,這樣直接點。
// 我們都放C://CSV文件夾里面吧
QString strDir = QString("%1/%2").arg("C://").arg("CSV");
// 先檢查有沒有文件夾存在,沒有就讓程序創(chuàng)建文件夾先
QDir dirCSV;
if (!dirCSV.exists(strDir))
dirCSV.mkpath(strDir);
// 使用時間格式進行csv文件命名吧
m_strFilePath = strDir + "/" + QString("csv%1.csv").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
// 因為是文件操作,安全一些都是加個鎖
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("");
// 文件不存在,第一次,我們就給他寫個列表名字,這樣csv文件打開時候查看的時候就比較清晰
strText = QString("DateTime,") + QString("Info");
in << strText << '\n';
file.close();
}
}
mutex.unlock();
二、CSV寫入
寫入的方式其實就是按照我們之前定義的格式寫入就行了,主要文件打開的方式就行了,讀取的也是一樣嗎,這里不做贅述。
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ù)進行分割。注意:csv文件其實就是文本文件,每行數(shù)據(jù)可以用逗號或者制表符進行分割。在讀取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進行標準化的讀寫,還是很簡單。
具體例如:
void mainwindow::OnExportBtnClicked()
{
//1.選擇導出的csv文件保存路徑
QString csvFile = QFileDialog::getExistingDirectory(this);
if(csvFile.isEmpty())
return;
//2.文件名采用系統(tǒng)時間戳生成唯一的文件
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文件 如果不存在則會自動新建一個新的文件
QFile file(csvFile);
if ( file.exists())
{
//如果文件存在執(zhí)行的操作,此處為空,因為文件不可能存在
}
file.open( QIODevice::ReadWrite | QIODevice::Text );
statusBar()->showMessage(tr("正在導出數(shù)據(jù)。。。。。。"));
QTextStream out(&file);
//4.獲取數(shù)據(jù) 創(chuàng)建第一行
out<<tr("UID,")<<tr("sysID,")<<tr("UsrID,")<<tr("MeterNum,")<<tr("CMD,\n");//表頭
//其他數(shù)據(jù)可按照這種方式進行添加即可
//5.寫完數(shù)據(jù)需要關閉文件
file.close();
}
到此這篇關于QT進行CSV文件初始化與讀寫操作的文章就介紹到這了,更多相關QT CSV文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言MFC導出dll回調(diào)函數(shù)方法詳解
這篇文章主要為大家介紹了C語言MFC導出dll回調(diào)函數(shù)方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

