QtableWidget中的表格数据导出成*.csv文件

这里是我使用的一个方法,取出所有单元格数据,保存为用逗号间隔,保存为csv格式,就可以用excel打开。

代码如下:

bool TableToExcle::exportExecl(QTableWidget *tableWidget, QString dirName, QString fileName)
{
    QDir dir(dirName);
    QString fullDirName = QDir::currentPath() + "/output/" + dirName;
    if (!dir.exists())
    {
        dir.mkdir(fullDirName);
    }

    QString dirFile = fullDirName + "/" + fileName + ".csv";
    QFile file(dirFile);
    bool ret = file.open(QIODevice::Truncate | QIODevice::ReadWrite);
    if(!ret)
    {
        qDebug() << "open failure";
        return ret;
    }

    QTextStream stream(&file);
    QString conTents;
    // 写入头
    QHeaderView * header = tableWidget->horizontalHeader() ;
    if (NULL != header)
    {
        for (int i = 0; i < header->count(); i++)
        {
            QTableWidgetItem *item = tableWidget->horizontalHeaderItem(i);
            if (NULL != item)
            {
                conTents += item->text() + ",";
            }
        }
        conTents += "\n";
    }

    // 写内容
    for (int row = 0; row < tableWidget->rowCount(); row++)
    {
        for (int column = 0; column < tableWidget->columnCount(); column++)
        {
            QTableWidgetItem* item = tableWidget->item(row, column);
            if (NULL != item )
            {
                QString str;
                if ((1 == column) || (2 == column))
                {
                    str = QDateTime::fromString(item->text(), "yyyy-MM-dd hh:mm:ss").toString("yyyyMMdd-hhMMss");
                }
                else
                {
                    str = item->text();
                }

                str.replace(","," ");
                conTents += str + ",";
            }
        }
        conTents += "\n";
    }
    stream << conTents;

    file.close();
    return true;
}

保存到csv文件为:


转载于:https://my.oschina.net/TomShine/blog/394753

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值