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文件为:


你可能感兴趣的:(QtableWidget中的表格数据导出成*.csv文件)