QXlsx对合并单元格的处理

以下代码是在项目中使用QXlsx对合并单元格的处理,处理的部分都加了注释


    void c_excel::ImportIPCNameInfo(modipcmrg *qWidget,QStandardItemModel *qModelList,QString qstrFilePath)
    {
    	QXlsx::Document xlsx(qstrFilePath);
    	QXlsx::CellRange range = xlsx.dimension();
    	int nrow = range.lastRow();
    	int ncol = range.lastColumn();
    	int nRowCout = qModelList->rowCount();
    	
    	/******合并单元格的内容处理******/
    	QXlsx::Workbook *xWorkBook = xlsx.workbook();
    	//默认使用第一张表格
    	QXlsx::Worksheet *xWorkSheet = static_cast(xWorkBook->sheet(0));
    	//获取到所有的合并单元格
    	QList qMergedCellsList = xWorkSheet->mergedCells();
    	
    	QMap qmap;
    	for(int i = 0; i < nRowCout; i++)
    	{
    		TAG_DEVICE_CHANNEL_IPC_24_INFO& ipcInfo = qModelList->item(i)->data().value();
    		QString ipcName = ipcInfo.qstrDeviceName;
    		QString ipcIp = ipcInfo.qstrIP;
    		unsigned int ipcProtocol = ipcInfo.nProtocolType;
    		auto &iter = qmap.find(ipcIp);
    		if(iter == qmap.end())
    		{
    			qmap.insert(ipcIp,QVariant::fromValue(ipcInfo));
    		}
    	}
    		
    	for(int j = 1;j <= nrow;j++)
    	{
    		QString qstrIp = "";
    		QString qstrName = "";
    		
    		for(int k=1; k<=ncol; k++)
    		{
    			if(k == 1)
    			{
    				qstrIp = xlsx.read(j,k).value();
    			}
    			else
    			{
    				if(qMergedCellsList.size() > 0)
    				{
    					bool bflag = false;
    					//合并单元格的内容处理
    					foreach(QXlsx::CellRange cellR, qMergedCellsList)
    					{
    						//合并单元格可通过第一行,最后一行,第一列,最后一列四个参数来确定合并的区域
    						int nFirstRow = cellR.firstRow();
    						int nLastRow = cellR.lastRow();
    						int nFirstCol = cellR.firstColumn();
    						int nLastCol = cellR.lastColumn();
    						//判断该单元格是否处于合并单元格中
    						if(nFirstRow <= j && j<= nLastRow && nFirstCol <= k && k<= nLastCol)
    						{
    							qstrName += xlsx.read(nFirstRow,nFirstCol).value();
    							bflag = true;
    						}
    					}
    					if(bflag)
    					{
    						continue;
    					}
    				}
    				
    				qstrName += xlsx.read(j,k).value();
    			}
    		}
    
    		auto &iter = qmap.find(qstrIp);
    		if(iter == qmap.end())
    		{
    			continue;
    		}
    
    		QVariant qvar = iter.value();
    		TAG_DEVICE_CHANNEL_IPC_24_INFO ipcInfo = qvar.value();
    		if(ipcInfo.qstrIP == qstrIp && !qstrName.isEmpty() && !qstrName.isNull() && qstrName != ipcInfo.qstrDeviceName)
    		{
    			if(ipcInfo.nProtocolType == UNS_DEVICE_NVRODLPRO)
    			{
    				ipcInfo.qstrDeviceName = QString::number(ipcInfo.nChannel) + QString("_")+qstrName;
    			}
    			else
    			{
    				ipcInfo.qstrDeviceName = qstrName;
    			}
    			QVariant tag = QVariant::fromValue(ipcInfo);
    
    			emit qWidget->mod_channel_info_import_export_signal(qWidget->GetProtocolType(),qWidget->GetDeviceID(),QVariant::fromValue(tag));
    		}
    	}
    	Sleep(500);
    	emit import_IPC_name_success_signal();

下面是我的表格格式,第一列之后可以随便合并
QXlsx对合并单元格的处理_第1张图片

你可能感兴趣的:(VS-Qt工作总结)