Use map to process data in the project

Scene reproduction

Project scenario:
Input a string of string data, return the corresponding set of data through the server and display it in the tableview view, and then put this set of data into the excel file specified in the specified format.


Problem Description

At the beginning, my idea was to read the data in the corresponding rows and columns of the tableview. The code logic is somewhat convoluted and the implementation is very complicated.

ui->tableView->model()->headerData(i,Qt::Horizontal,Qt::DisplayRole).toString();
/*
通过遍历tableView的方法来获取所有列标题,同时获取所有数据.
*/

Cause Analysis and Solutions

The efficiency of processing data is extremely low

Use the STL associated container mapto put the data into the container at the same time as the data is acquired map, and then directly take out the data in the file when writing to the file map.

        QMap<QString,QString> map;//缓存所有列的聚合数据
        for (int i=0;i<columns.size();i++) {
            map.insert(columns.at(i),"");
        }
        int index=1;//当前写入excle第几列的指针
        for (int row=0;row<rowcount;row++) {
            LabelData labelData=  teamData.at(row);
            QStringList fieldValues = labelData.printValues.split(",");
            for (int j=0;j<columns.size();j++) {//遍历字段
                //设置列名
                QString field = columns.at(j);
                QAxObject *fieldName = worksheet->querySubObject("Cells(int,int)", 1, index);
                fieldName->setProperty("Value", field.append("-").append(QString::number(row)));
                //设置值
                QAxObject *fieldValue = worksheet->querySubObject("Cells(int,int)", 2, index);
                fieldValue->setProperty("Value", fieldValues.at(j));
                //聚合列数
                if(row==rowcount-1){//最后一个聚合数据不需要换行
                    map[columns.at(j)]=map[columns.at(j)].append(fieldValues.at(j));
                }else {
                   map[columns.at(j)]=map[columns.at(j)].append(fieldValues.at(j)).append("\n");
                }
                index++;//移动列指针
            }
        }

おすすめ

転載: blog.csdn.net/Stephen8848/article/details/123932575