天天看點

Qt如何将資料儲存成CSV檔案

一、csv檔案

csv檔案是逗号分隔值(Comma-Separated Values,CSV)檔案的縮寫,其檔案以純文字形式存儲表格資料(數字和文本),各個字段用逗号進行分割,采用回車進行換行。由于采用純文字記錄,csv檔案可以很友善的被文本處理工具、excel等工具識别。

二、Qt中導出csv檔案

在Qt中打開與儲存csv檔案十分友善,直接按照普通文本的形式操作,用QTextStream進行标準化的讀寫,還是很簡單。

具體例如:

void mainwindow::OnExportBtnClicked()
{
    //1.選擇導出的csv檔案儲存路徑
    QString csvFile = QFileDialog::getExistingDirectory(this);
    if(csvFile.isEmpty())
       return;
    
    //2.檔案名采用系統時間戳生成唯一的檔案
    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())
    {
        //如果檔案存在執行的操作,此處為空,因為檔案不可能存在
    }
    file.open( QIODevice::ReadWrite | QIODevice::Text );
    statusBar()->showMessage(tr("正在導出資料。。。。。。"));
    QTextStream out(&file);
    
    //4.擷取資料 建立第一行
    out<<tr("UID,")<<tr("sysID,")<<tr("UsrID,")<<tr("MeterNum,")<<tr("CMD,\n");//表頭
    //其他資料可按照這種方式進行添加即可

    //5.寫完資料需要關閉檔案
    file.close();
}

           

繼續閱讀