Search code examples
c++csvqt4export

Export data from qtablewidget to csv


I have a little problem with export data to csv (comma-separated values). All data was exported, but headers and name of rows from QTableWidget don't. I need headers of columns and rows.

Do you have any idea how to get name headers of columns and name of rows? Here is my code:

QFile f( "money.csv" );

if (f.open(QFile::WriteOnly | QFile::Truncate))
{
    QTextStream data( &f );
    QStringList strList;

    for( int r = 0; r < ui->tableWidget->rowCount(); ++r )
    {
        strList.clear();
        for( int c = 0; c < ui->tableWidget->columnCount(); ++c )
        {
            strList << "\" "+ui->tableWidget->item( r, c )->text()+"\" ";
        }
        data << strList.join( ";" )+"\n";
    }
    f.close();
}

Solution

  • You can use QTableWidget::horizontalHeaderItem(int column), which returns the header item for the column column.

    QTableWidget * table = ui->tableWidget;
    
    for( int c = 0; c < widget->columnCount(); ++c )
    {
        strList << 
                "\" " +
                table->horizontalHeaderItem(c)->data(Qt::DisplayRole).toString() +
                "\" ";
    }
    
    data << strList.join(";") << "\n";