Hello All,
I am trying to create a tool that will put all of the selected attribute information from one map ( from 30+ features classes of varying types, ie. polygon, polyline, point) into one, or multiple excel files. In my mind, it would work best if each feature class was it's own tab within a single excel file. So I can look at the file and see what types of features have been selected with in the boundary I am using.
I can think how to do this manually, but It would really streamline our process to be able to automate this. Has anyone done anything similar and would be willing to share some code? I'm a beginner python user with just enough knowledge to be dangerous lol.
Thank you!
My first thought would be to cycle through all the layers and export to pandas data frames, and then go to excel from there.
Have you looked at tutorials like this?
https://towardsdatascience.com/how-to-build-a-multi-tabbed-excel-file-using-pandas-731391c2cc53
Using @Kara_Shindle's brilliant idea-
import arcpy
import pandas as pd
from arcgis.features import GeoAccessor, GeoSeriesAccessor
dataframes = {}
aprx = arcpy.mp.ArcGISProject(r'CURRENT')
for m in aprx.listMaps():
for lyr in m.listLayers():
lyrdesc = arcpy.Describe(lyr)
# Filter to featurelayers and skip rasters
if lyrdesc.dataType == 'FeatureLayer':
# check if the layer has a selection
if lyrdesc.FIDSet:
# Create df of selected data using the FIDSet
object_ids = lyrdesc.FIDSet.replace(";", ",") # format to SQL
# arcpy.AddMessage(object_ids)
# either use catalogPath or path to get to the feature layer path
sdf = pd.DataFrame.spatial.from_featureclass(lyrdesc.catalogPath, where_clause=f'OBJECTID IN ({object_ids})')
# Add to the dataframe dictionary
dataframes[lyrdesc.name] = sdf
# create the tabbed csv output by iterating over the dataframes dictionary
with pd.ExcelWriter(r'C:\Users\...\Documents\selected_data.xlsx', engine='xlsxwriter') as writer:
for lyr, df in dataframes.items():
df.to_excel(writer, sheet_name=f'{lyr}', index=False)