Arcpy adds corresponding fields to vector elements in batches based on the table fields in excel

It is possible to use Arcpy to add the fields in the Excel table to the vector elements in batches and fill in the corresponding content to the attribute table of the elements. The following is a simple code, assuming an Excel table with fields and data and a vector feature layer to be added in batches:
import arcpy
import xlrd

# Set input data path
excel_file = r"C:\data\attributes.xlsx" # Excel table containing fields and data
feature_class = r"C:\data\features.shp" # Vector feature layer to be added in batches

# 打开Excel表格
workbook = xlrd.open_workbook(excel_file)
worksheet = workbook.sheet_by_index(0)

# Get the field name and value of the Excel table
field_names = [str(cell.value) for cell in worksheet.row(0)]
field_values ​​= [[str(cell.value) for cell in worksheet.row(row_id)] ​​for row_id in range(1, worksheet. nrows)]

# Add field to feature class
for field_name in field_names:
    arcpy.AddField_management(feature_class, field_name, "TEXT")

# Open the edit session of the feature class
with arcpy.da.Editor(arcpy.env.workspace) as edit_session:
    # Update the attribute table of the feature class
    with arcpy.da.UpdateCursor(feature_class, field_names) as cursor:
        for row_id, row in enumerate (cursor):
            if row_id < len(field_values):
                row = field_values[row_id]
                cursor.updateRow(row)
 

In the above code, the path of the input data is first set, that is, the Excel table containing fields and data and the vector feature layer to be added in batches. Then, use the `xlrd` module to open the Excel sheet and get the field names and values. Next, fields are added to the feature class one by one via the `AddField_management` function. Finally, use `UpdateCursor` to iterate through each row of the feature class and update the attribute table of the feature class according to the corresponding data in the Excel sheet.

Note that paths and filenames in the code should be modified accordingly for your own data. In addition, the field type is set to "TEXT". If you need to add other types of fields (such as integer, floating point, etc.), you can modify the third parameter of the `AddField_management` function accordingly. Also, make sure the field names of the Excel sheet exactly match the field names of the feature class.

Guess you like

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