QT——csv文件读取保存到链表中

定义一个结构体,用来储存读到的数据

struct Data
{
	QString name;
	QString IDName;
	QString ploneNum;
	QString address;
	int buildingNum;
	int tierNum;
	int roomNum;
	int danyuanNum;

	Data() {}
	Data(QString P_name, QString P_IDName, QString P_ploneNum, QString P_address, int p_tierNum, int p_roomNum)
	{
		name = P_name;
		IDName = P_IDName;
		ploneNum = P_ploneNum;
		address = P_address;
		tierNum = p_tierNum;
		roomNum = p_roomNum;
	}
};

函数实现

void readData()
{
	tenantInfoList.clear();                 //             tenantInfoList 用于保存数据的容器,读取前先清一遍
	QFile fileData("text.csv");
	QString allString;
	if (fileData.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		allString = fileData.readAll();
		fileData.close();
	}
	QStringList personList = allString.split("\n");                  //将读取的每一行数据保存到list中,
	for (int i = 0; i < personList.size(); i++)
	{
		//qWarning() << personList[i];
		QStringList personInfos = personList[i].split(",");    
		if (personInfos.size() < 6)
		{
			continue;
		}
		Data data;
		data.name = personInfos[0];
		data.IDName = personInfos[1];
		data.ploneNum = personInfos[4];
		data.address = personInfos[5];
		int startIdx = personInfos[2].indexOf(QStringLiteral("元"));
		int cengIdx = personInfos[2].indexOf(QStringLiteral("层"));
		if (cengIdx != -1) startIdx = cengIdx;
		int endIdx = personInfos[2].indexOf(QStringLiteral("室"));
		QString roomStr = personInfos[2].mid(startIdx + 1, endIdx - startIdx - 1);
		qWarning() << roomStr;
		data.roomNum = roomStr.toShort();
		data.tierNum = data.roomNum / 100;
		startIdx = personInfos[2].indexOf(QStringLiteral("幢"));
		endIdx = personInfos[2].indexOf(QStringLiteral("单"));
		data.danyuanNum = personInfos[2].mid(startIdx + 1, endIdx - startIdx - 1).toShort();
		startIdx = personInfos[2].indexOf(QStringLiteral("家"));
		endIdx = personInfos[2].indexOf(QStringLiteral("幢"));
		data.buildingNum = personInfos[2].mid(startIdx + 1, endIdx - startIdx - 1).toShort();
		tenantInfoList.push_back(data);
	}
}

你可能感兴趣的:(QT)