Qt 5写CSV文件

    //获取创建的csv文件名
    QString fileName = QFileDialog::getSaveFileName(this, tr("Excel file"), qApp->applicationDirPath (),
                                                     tr("Files (*.csv)"));

    if (fileName.isEmpty())
    {
        return;
    }

    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        return;
    }

    QTextStream textStream(&file);
    QString tableContents;
    QHeaderView * headerView = ui->tableWidget->horizontalHeader();

    if (headerView)
    {
        for (int i = 0; i < headerView->count(); i++ )
        {
            QTableWidgetItem *item = ui->tableWidget->horizontalHeaderItem(i);
            if (!item)
            {
                continue;
            }
            tableContents += item->text() + ",";
        }
        tableContents += "\n";
    }

    int rowCount = ui->tableWidget->rowCount();
    int colCount = ui->tableWidget->columnCount();

    for(int j = 0; j < rowCount; j++)
    {
        for(int k = 0; k < colCount; k++)
        {
            QTableWidgetItem* item = ui->tableWidget->item(j, k);
            if ( !item )
                continue;
            QString str = item->text().simplified();
            //str.replace(","," ");
            tableContents += str + ",";
        }
        tableContents += "\n";
    }

    //  一次性写到文件里;不要在for循环里去频繁调用QTextStream的对象去写文件,那样很容易导致程序崩溃。
    textStream << tableContents;
    file.close();

 

你可能感兴趣的:(Qt学习)