乐于分享
好东西不私藏

openclaw根据Excel表格ArcGIS 创建数据库GDB

openclaw根据Excel表格ArcGIS 创建数据库GDB

"""根据 Excel 属性结构表创建 ArcGIS 要素类功能:读取 Excel 中的字段定义,创建带别名和坐标系的空要素类"""import arcpyimport pandas as pdimport os# ==================== 配置区域 ====================输出路径desktop_gis = r"C:\Users\yl\Desktop\GIS"gdb_name = "d.gdb"gdb_path = os.path.join(desktop_gis, gdb_name)# Excel 文件路径excel_dir = r"E:\2026\Pro\data\data"坐标系 WKIDspatial_ref_wkid = 4546  # CGCS2000_3_Degree_GK_CM_111E# ================================================def find_excel_file(base_path):"""查找 chp5 目录下的 Excel 文件(排除临时文件)"""for item in os.listdir(base_path):if "chp5" in item:            chp5_path = os.path.join(base_path, item)for file in os.listdir(chp5_path):if file.endswith(".xlsx"and not file.startswith("~$"):return os.path.join(chp5_path, file)return Nonedef parse_excel(excel_path):"""解析 Excel 文件,提取要素类配置信息"""xl = pd.ExcelFile(excel_path)    sheet_names = xl.sheet_names    fc_configs = []for sheet in sheet_names:读取前 3 行获取要素信息df_header = pd.read_excel(excel_path, sheet_name=sheet, nrows=3, header=None) 0: 要素名称代码fc_code = str(df_header.iloc[01]).strip() if pd.notna(df_header.iloc[01]) else sheet 1: 别名fc_alias = str(df_header.iloc[11]).strip() if pd.notna(df_header.iloc[11]) else "" 2: 要素类型fc_type_raw = str(df_header.iloc[21]).strip() if pd.notna(df_header.iloc[21]) else ""转换要素类型if fc_type_raw == "or "in fc_type_raw:            geom_type = "POINT"elif fc_type_raw == "线or "线in fc_type_raw:            geom_type = "POLYLINE"elif fc_type_raw == "or "in fc_type_raw or "多边形in fc_type_raw:            geom_type = "POLYGON"else:            geom_type = "POLYGON"  默认面读取字段定义(从第 4 行开始,跳过表头行 3df_fields = pd.read_excel(excel_path, sheet_name=sheet, skiprows=4, header=None)        fields = []for idx, row in df_fields.iterrows():if pd.notna(row.iloc[0]) and pd.notna(row.iloc[1]) and pd.notna(row.iloc[2]):                field_order = row.iloc[0]                field_alias = str(row.iloc[1]).strip() if pd.notna(row.iloc[1]) else ""field_name = str(row.iloc[2]).strip() if pd.notna(row.iloc[2]) else ""field_type_raw = str(row.iloc[3]).strip() if pd.notna(row.iloc[3]) else "Char"field_length = int(row.iloc[4]) if pd.notna(row.iloc[4]) else None跳过表头行if field_name in ["字段名称""字段代码""NaN""nan"""]:continue转换字段类型if field_type_raw in ["Char""String""Text"]:                    field_type = "TEXT"elif field_type_raw in ["Int""Integer""Long"]:                    field_type = "LONG"elif field_type_raw in ["Float""Single"]:                    field_type = "FLOAT"elif field_type_raw in ["Double"]:                    field_type = "DOUBLE"elif field_type_raw in ["Date"]:                    field_type = "DATE"else:                    field_type = "TEXT"fields.append({"name": field_name,"type": field_type,"length": field_length,"alias": field_alias                })        fc_configs.append({"sheet_name": sheet,"fc_code": fc_code,"fc_alias": fc_alias,"geom_type": geom_type,"fields": fields        })return fc_configsdef create_gdb(gdb_path):"""创建文件地理数据库"""if arcpy.Exists(gdb_path):        arcpy.Delete_management(gdb_path)        print(f"已删除现有的地理数据库:{gdb_path}")    arcpy.CreateFileGDB_management(os.path.dirname(gdb_path), os.path.basename(gdb_path))    print(f"已创建地理数据库:{gdb_path}")def create_featureclasses(gdb_path, fc_configs, spatial_ref):"""创建要素类并添加字段"""for fc_config in fc_configs:        fc_name = fc_config["fc_code"]        fc_alias = fc_config["fc_alias"]        geom_type = fc_config["geom_type"]        print(f"\n创建要素类:{fc_name} (别名:{fc_alias}) ({geom_type})")创建要素类fc_path = arcpy.CreateFeatureclass_management(            out_path=gdb_path,            out_name=fc_name,            geometry_type=geom_type,            spatial_reference=spatial_ref        ).getOutput(0)        print(f"  路径:{fc_path}")设置要素类别名if fc_alias:            arcpy.AlterAliasName(fc_path, fc_alias)            print(f"  已设置别名:{fc_alias}")添加字段for field in fc_config["fields"]:try:if field["type"] == "TEXT" and field["length"]:                    arcpy.AddField_management(fc_path, field["name"], field["type"],                                             field_length=field["length"],                                             field_alias=field["alias"])elif field["type"in ["FLOAT""DOUBLE""LONG""DATE"]:                    arcpy.AddField_management(fc_path, field["name"], field["type"],                                             field_alias=field["alias"])else:                    arcpy.AddField_management(fc_path, field["name"], field["type"],                                             field_alias=field["alias"])                print(f"    添加字段:{field['name']} ({field['type']}) - {field['alias']}")except Exception as e:                print(f"    添加字段 {field['name']失败:{e}")def verify_gdb(gdb_path):"""验证地理数据库内容"""print("\n\n=== 地理数据库内容 ===")    arcpy.env.workspace = gdb_path    fcs = arcpy.ListFeatureClasses()if fcs:for fc in fcs:            fc_path = os.path.join(gdb_path, fc)            desc = arcpy.Describe(fc_path)            print(f"\n{fc}")            print(f"  别名:{desc.aliasName}")            print(f"  几何类型:{desc.shapeType}")            print(f"  坐标系:{desc.spatialReference.name} (WKID: {desc.spatialReference.factoryCode})")            fields = arcpy.ListFields(fc_path)for field in fields:if field.name not in ["OID""Shape""Shape_Length""Shape_Area"]:                    print(f"    - {field.name}{field.type} (别名:{field.aliasName})")else:        print("未找到要素类")def main():"""主函数"""print("=" 60)    print("ArcGIS 要素类创建工具")    print("=" 60)查找 Excel 文件excel_path = find_excel_file(excel_dir)if not excel_path:        print("错误:未找到 Excel 文件")returnprint(f"\nExcel 文件:{excel_path}")创建空间参考spatial_ref = arcpy.SpatialReference(spatial_ref_wkid)    print(f"使用坐标系:{spatial_ref.name} (WKID: {spatial_ref_wkid})")解析 Excelfc_configs = parse_excel(excel_path)    print(f"\n解析到 {len(fc_configs)个要素类配置")创建地理数据库create_gdb(gdb_path)创建要素类create_featureclasses(gdb_path, fc_configs, spatial_ref)验证结果verify_gdb(gdb_path)    print(f"\n\n完成!地理数据库位于:{gdb_path}")if __name__ == "__main__":需要 ArcGIS Pro Python 环境运行main()