首页 > 技术知识 > 正文

Qt表格读写(CSV格式)

CSV文件是文本类型的数据文件,因此具有读写速度快、格式相对标准等特点,适用于多种场合的数据读写及分析。CSV文件也叫逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。 Qt中CSV格式读写:

void read(){ QString fileName = “test.csv” macAddressFile.setFileName(fileName); if(!macAddressFile.open(QFile::ReadWrite | QFile::Text)) { printfLog(QString::fromLocal8Bit(“文件打开失败,请重新打开软件”)); return; } QTextStream textStream (&macAddressFile); //设置编码格式 textStream->setCodec(“utf8”);//GB2312 while(!textStream->atEnd()){ //读取一行 QStringList tempData = textStream->readLine().split(“,”); for(int i = 0;i < tempData .count();i++) { //读取每一列 qDebug() << tempData .at(i) } } } void write(){ QString fileName = “test.csv” macAddressFile.setFileName(fileName); if(!macAddressFile.open(QFile::ReadWrite | QFile::Text)) { printfLog(QString::fromLocal8Bit(“文件打开失败,请重新打开软件”)); return; } QTextStream textStream (&macAddressFile); //设置编码格式 textStream->setCodec(“utf8”);//GB2312 QStringList list; for (int i=0;i<10;i++) { //添加列 list<< QString::fromLocal8Bit(“第%1列”).arg(i); } //添加行 textStream<< list.join(“,”)<<“\r\n”; }
<

以上代码运行后使用wps打开的csv: Qt表格读写(CSV格式) 记事本下打开的csv: Qt表格读写(CSV格式)1

猜你喜欢