一、打开文件夹返回文件名
代码如下:
void MainWindow::on_btn_open_csvFile_clicked() { QString fileName = QFileDialog::getOpenFileName( this,tr("选择要打开的文件"), QDir::currentPath(), tr("文本文件(*.txt);;所有文件(*.*)")); if (!fileName.isEmpty()) { this->fileName = fileName; qDebug()<<"filename:"<<fileName; } }
二、CSV文件格式如图:
三、QT读CSV文件,代码如下
void MainWindow::on_btn_get_csv22_clicked() { QVector<double> x, y,y2; QStringList csvList; csvList.clear(); //解析CSV文件 QFile csvFile(this->fileName22); if(csvFile.open(QIODevice::ReadWrite)) { QTextStream stream(&csvFile); while(!stream.atEnd()) { csvList.push_back(stream.readLine()); } csvFile.close(); } else { QMessageBox::about(nullptr,"csv 文件","打开失败"); } int i = 0; Q_FOREACH(QString str,csvList) { i = i + 1; QStringList valsplit = str.split(","); if(i>3) { x.push_back(valsplit[0].toDouble()); y.push_back(valsplit[1].toDouble()); y2.push_back(valsplit[2].toDouble()); } } }
四、QT写CSV文件,代码如下:
void MainWindow::on_btn_geneate_csvFile22_clicked() { QDateTime datetime = QDateTime::currentDateTime(); QString timestr = datetime.toString("ddHHmmzzz"); // QFile data(QString("E:\QT\qcptest2\") + "two" + timestr + ".csv"); // 以上两行用时间戳作为文件名 this->fileName = "E:\QT\qcptest2\cos.csv"; QFile data(this->fileName22); if(data.open(QFile::WriteOnly | QFile::Truncate)) // 打开文件 { QTextStream out(&data); // 输入流 double t = 0; double y1; double y2; double intv = 1; for (int i = 0; i < 100; ++i) { y1 = qSin(t); y2 = qCos(t); out <<QString::number(t)<<"," << QString::number(y1)<<"," << QString::number(y2)<<","<< " "; t = t + intv; } } data.close(); }