Qt 将数据写入CSV
Qt UDP接收数据保存到CSV文件
·
功能模块
1. 将自定义数据写入一个或多个CSV文件;
2. 启用线程将数据写入CSV文件
3. 通过UPD组播的形式将接收到数据
原则不能变! 上代码!! 在自己记录的同时也希望对大家有帮助!!!
.pro 添加network模块
QT += core gui network
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket>
#pragma pack(1)//字节对齐
struct RecvParame
{
char A;
double B;
float C;
char D;
int E;
};
#pragma pack()
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void recvMultiCastMsg();//通过组播形式接收数据保存到csv
void on_threadRecordBtn_clicked();//启用线程写CSV
void on_readCsvBtn_clicked();//读取CSV
void on_MultipleWriteBtn_clicked();//写多个CSV文件
void on_singleWriteBtn_clicked();//写单个CSV文件
private:
Ui::MainWindow *ui;
QUdpSocket *recvSocket;//UdpSocket
QHostAddress m_MultiRecvIP = QHostAddress("224.0.2.106");//组播IP
quint16 recvPort = 12006;//端口
QString fileContent = "";//写入CSV的内容
int writeNum = 0;//写入CSV的行数
int nFileName = 1;//文件名称(1、2、3.....)
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QDebug>
#include <QDateTime>
#include <thread>
QFile m_file_save;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
recvSocket = new QUdpSocket(this);
recvSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, 0);
bool bindResult = recvSocket->bind(QHostAddress::AnyIPv4, recvPort, QUdpSocket::ShareAddress);// 组播绑定
if (bindResult)
{
bool isTrue = recvSocket->joinMulticastGroup(m_MultiRecvIP);// 加入组播
if (!isTrue)//加入组播失败
{
recvSocket->close();
}
else
{
connect(recvSocket, SIGNAL(readyRead()), this, SLOT(recvMultiCastMsg()));
}
}
else {//IP、端口连接失败
recvSocket->close();
}
}
MainWindow::~MainWindow()
{
if(m_file_save.isOpen())
{
m_file_save.close();
}
delete ui;
}
/* 通过组播形式接收数据保存到csv */
void MainWindow::recvMultiCastMsg()
{
QString file_top = "";
quint64 length = -1;
QString strFileName = "./data/" + QString::number(nFileName) + ".csv";
m_file_save.setFileName(strFileName);
if(!m_file_save.open(QIODevice::ReadWrite))
qDebug()<<"文件打开失败";
else
qDebug()<<"文件打开成功";
file_top = "A,B,C,D,E\r\n"; //title
length = m_file_save.write(file_top.toUtf8(), file_top.length());
if(length == -1)
qDebug()<<"写入文件失败";
else
qDebug()<<"写入文件成功";
while (recvSocket->hasPendingDatagrams() >0) {
QByteArray datagram;
RecvParame recvMsg;
datagram.resize(recvSocket->pendingDatagramSize());
recvSocket->readDatagram(datagram.data(), datagram.size(), &m_MultiRecvIP, &recvPort);
memcpy(&recvMsg, datagram.data(), sizeof(RecvParame));
fileContent += recvMsg.A + ",";
fileContent += QString::number(recvMsg.B,'.',3) + ",";
fileContent += QString::number(recvMsg.C,'f',3) + ",";
fileContent += recvMsg.D + ",";
fileContent += QString::number(recvMsg.E);
fileContent += "\r\n";
quint64 length = -1;
length = m_file_save.write(fileContent.toLatin1(), fileContent.length());
if(length == -1) qDebug()<<"写入文件失败";
else qDebug()<<"写入文件成功";
for(; writeNum++ > 10000; writeNum++)
{
m_file_save.close();
fileContent = "";
nFileName++;
writeNum = 0;
}
}
}
/* 写单个CSV文件 */
void MainWindow::on_singleWriteBtn_clicked()
{
QString strFilePath = "./RecordedData/";//文件夹路径
QString strFileName = strFilePath + QString::number(nFileName) + ".csv";//需要记录的文件名称
QVector <int> ch1;
QVector <QVector <int>> ch2;
for (int i = 0; i <10000;i++) {//行
for (int j = 0;j<60;j++) {//列
ch1.push_back(j);
}
ch2.push_back(ch1);
}
QString file_content = "";
qint64 file_point_pos = 1;//从第一行开始
qint64 length = -1;
file_point_pos = m_file_save.size();
m_file_save.seek(file_point_pos);
for (int i = 0; i <10000;i++) {//行
for (int j = 0;j<57;j++) {//列
file_content+=QString("%1").arg(ch1.at(j)) + ",";
}
file_content += "\r\n";
}
qDebug("file_content.length() = %d\n", file_content.length());
length = m_file_save.write(file_content.toLatin1(), file_content.length());
if(length == -1){
qDebug()<<"写入文件失败";
}else{
qDebug()<<"写入文件成功";
}
m_file_save.close();
}
/* 写多个CSV文件 */
void MainWindow::on_MultipleWriteBtn_clicked()
{
while (1) {
QString file_top = "";
quint64 length0 = -1;
QString strFileName = "./data/" + QString::number(nFileName) + ".csv";//文件名称
m_file_save.setFileName(strFileName);
if(!m_file_save.open(QIODevice::ReadWrite))
qDebug()<<"文件打开失败";
else
qDebug()<<"文件打开成功";
file_top = "A,B,C,D,E,F\r\n";//Title
length0 = m_file_save.write(file_top.toUtf8(), file_top.length());
if(length0 == -1) qDebug()<<"写入文件失败";
else qDebug()<<"写入文件成功";
fileContent += "1,";
fileContent += "2,";
fileContent += "3,";
fileContent += "4,";
fileContent += "5,";
fileContent += "6";
fileContent += "\r\n";
quint64 length = -1;
length = m_file_save.write(fileContent.toLatin1(), fileContent.length());
if(length == -1)
qDebug() <<"写入文件失败";
else
qDebug()<<"写入文件成功" << QString::number(writeNum);
writeNum++;
if(writeNum > 5000)//每个CSV文件写5000行
{
m_file_save.close();
fileContent = "";//清空内容
nFileName++;//换个文件继续保存CSV
writeNum = 0;//从新CSV文件0行开始
}
}
}
//接收数据线程
void Thread_RecvData()
{
int nFileName= 1;//初始文件名称
QString fileContent = "";
QString file_top = "";//Title
quint64 fileTopLength = -1;
int writeNum = 0;
int num =1;
while (num!=-1) {
QString strFileName = "./data/" + QString::number(nFileName) + ".csv";
m_file_save.setFileName(strFileName);
if(!m_file_save.open(QIODevice::ReadWrite))
qDebug()<<"文件打开失败";
else
qDebug()<<"文件打开成功";
file_top = "A,B,C,D,E,F\r\n";
fileTopLength = m_file_save.write(file_top.toUtf8(), file_top.length());
if(fileTopLength == -1)
qDebug()<<"写入文件失败";
else
qDebug()<<"写入文件成功";
fileContent += "1,";
fileContent += "1,";
fileContent += "1,";
fileContent += "1,";
fileContent += "1,";
fileContent += "1";
fileContent += "\r\n";
quint64 fileContentLength = -1;
fileContentLength = m_file_save.write(fileContent.toLatin1(), fileContent.length());
if(fileContentLength == -1)
qDebug() <<"写入文件失败";
else
qDebug()<<"写入文件成功" << QString::number(writeNum);
writeNum++;
if(writeNum > 100)
{
m_file_save.close();
fileContent = "";
nFileName++;
writeNum = 0;
}
if(nFileName ==3)
num = -1;
}
}
/* 启用线程写CSV */
void MainWindow::on_threadRecordBtn_clicked()
{
std::thread threadRecvData(Thread_RecvData);
threadRecvData.detach();
}
/* 读取CSV */
void MainWindow::on_readCsvBtn_clicked()
{
QString directoryPath = "./data/";
// 获取CSV文件列表并读取数据
QDir directory(directoryPath);
QStringList csvFiles = directory.entryList(QStringList() << "*.csv", QDir::Files);
foreach (const QString& csvFile, csvFiles) {
QFile file(directoryPath + "/" + csvFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();//一行一行的读取
if(line != "A")
qDebug() << line;
}
file.close();
}
}
}
mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="singleWriteBtn">
<property name="geometry">
<rect>
<x>230</x>
<y>240</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>单文件记录</string>
</property>
</widget>
<widget class="QPushButton" name="MultipleWriteBtn">
<property name="geometry">
<rect>
<x>230</x>
<y>290</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>多文件记录</string>
</property>
</widget>
<widget class="QPushButton" name="threadRecordBtn">
<property name="geometry">
<rect>
<x>230</x>
<y>340</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>线程记录</string>
</property>
</widget>
<widget class="QPushButton" name="readCsvBtn">
<property name="geometry">
<rect>
<x>470</x>
<y>330</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>读取CSV</string>
</property>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui>

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)