QGIS batch connects the content in EXCEL to the corresponding vector element attribute table

To batch connect the contents of the Excel table to the attribute table of the corresponding vector elements in QGIS, you can use PyQGIS programming to complete. The following is the detailed sample code:


from qgis.core import QgsVectorLayer, QgsProject
import csv

# Set the vector layer file path
layer_file = '/path/to/your_vector_layer.shp'
# Set the Excel file path
excel_file = '/path/to/your_excel_file.xlsx'
# Set the field name for connection (Excel and vector layer shared field)
join_field = 'common_field'

# Load vector layer
layer = QgsVectorLayer(layer_file, 'Vector Layer', 'ogr')

# Create a dictionary to store data in Excel (according to the join field)
excel_data = {}
with open(excel_file, 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        key = row[join_field]
        excel_data [key] = row

# Enable editing mode
layer.startEditing()

# Traverse the features in the layer
for feature in layer.getFeatures():
    field_value = feature[join_field]
    
    # Check whether the join field value of the feature exists in the Excel data
    if field_value in excel_data:
        excel_row = excel_data[field_value]

        # 更新要素的属性值
        for field_name in excel_row:
            if field_name != join_field:
                field_index = layer.fields().lookupField(field_name)
                if field_index != -1:
                    layer.changeAttributeValue(feature.id(), field_index, excel_row[field_name])

# Save changes and stop editing mode
layer.commitChanges()
layer.stopEditing()

# Optional: save the updated layer
QgsProject.instance().addMapLayer(layer)
layer.updateFields()

# Note that the above code needs to ensure that the QGIS Python environment has been installed and configured correctly, and the required libraries have been imported. Please modify the file path and connection field name in the code according to the actual situation.

The code uses the `csv` library to read the data in the Excel file and store the data in a dictionary based on the join fields. Then, update the attribute value of the feature by traversing the feature in the vector layer and matching with the data in the dictionary. Finally, there is an option to save the updated layer. Please modify the file path and connection field name in the code according to the actual situation to suit your situation, and make sure that the required dependent libraries have been installed.

Guess you like

Origin blog.csdn.net/weixin_58851039/article/details/131389644