QT读写csv文件(文本文件)

//写数据
void MainWindow::on_pushButton_clicked()
{
    if(dataMap.size()<=0){
        QMessageBox::information(this,"","请先进行读数据操作!",NULL);
        return;
    }
    QFile file("C:/20171114.csv");
    QTextStream textStream;
    if(!file.open(QFile::WriteOnly | QFile::Truncate | QFile::Text)){
        QMessageBox::information(this,"","无生成盘符,应生成在C:/20171114.csv",NULL);
    }else{
        textStream.setDevice(&file);
        textStream.setCodec("GB2312");
        QMap<QString,int>dataNumMap;
 
  
        for(auto it = dataMap.begin();it != dataMap.end();++it){
            dataNumMap.insert(it.key(),it.value().size());
        }
        int maxNum = dataNumMap[dataNumMap.firstKey()];
        for(auto it = dataMap.begin();it != dataMap.end();++it){
            int temp = dataNumMap[it.key()];
            if(maxNum <= temp)
                maxNum = temp;
        }
        QString headerStr = "SevRNP,Number";
        for(int i=1;i<=maxNum;i++){
            headerStr = headerStr + ",TagRNP" + QString::number(i);
        }
        textStream << headerStr +"\n";
        //写数据
        QString dataStr;
        for(auto it = dataMap.begin();it != dataMap.end();++it){
            dataStr = it.key()+","+QString::number(it.value().size());
            for(int i=0;i 
  
                QStringList value = it.value();
                dataStr += ","+value.at(i);
            }
            textStream << dataStr +"\n";
            dataStr.clear();
        }
    }
    file.close();
    this->close();
    QMessageBox::information(this,"","文件生成在C:/20171114.csv",NULL);
}
 
  
//读取数据
 
  
void MainWindow::on_pushButton_2_clicked()
{
    QFile file("C:/20171113.csv");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QMessageBox::information(this,"","文件放错位置,应放置C:/20171113.csv",NULL);
    }else{
        QTextStream textStream(&file);
        textStream.setCodec("GB2312");
        textStream.readLine();
        //读数据
        QStringList firstData = textStream.readLine().split(",");
        SevRNP = firstData.at(0);
        TagRNPList.append(firstData.at(1));
        while(!textStream.atEnd()){
            QStringList tempData = textStream.readLine().split(",");
            if(tempData.at(0) == SevRNP){
                TagRNPList.append(tempData.at(1));
                continue;
            }
            dataMap.insert(SevRNP,TagRNPList);
            SevRNP = tempData.at(0);
            TagRNPList.clear();
            TagRNPList.append(tempData.at(1));
        }
        QMessageBox::information(this,"","数据读取完成,请写数据生成文件!",NULL);
    }
    file.close();
//    QString len ;
//    for(auto it = dataMap.begin();it != dataMap.end();++it){
//        len += QString::number(it.value().size())+",";
//    }
}

你可能感兴趣的:(QT,C++)