Using field info to only get certain fields

4967
4
11-21-2014 09:21 AM
KristenE
New Contributor III

I have  a feature class that I would like to export the attributes to Excel, while excluding certain fields. I know I could make a copy of the feature class and delete fields, but I would like to use the field info object to exclude the unnecessary fields while creating a table view. The following code still exports all the fields, can you tell me what I am missing?

After creating the table view I have tried, using copy rows instead of export to excel and got the same results. I also tried fieldinfo.removeField(index) for the fields I want to exclude but that returned an error (RuntimeError: ERROR 999999: Error executing function). Thanks for your help.

#---- Make Table View that only contains the needed fields and copy to Excel table

# Get the fields from the input feature class

fields= arcpy.ListFields(in_fc)

# Create a fieldinfo object

fieldinfo = arcpy.FieldInfo()

# Iterate through the fields and set them to fieldinfo

for field in fields:

    # If field name is in list of fields to keep,

    if field.name in out_fields:

        # Add to fieldinfo object

        fieldinfo.addField(field.name, field.name, "VISIBLE", "")

# Make the table view with only desired fields

arcpy.MakeTableView_management(in_fc, "table_view", field_info = fieldinfo)

# Copy to Excel table

arcpy.TableToExcel_conversion("table_view", out_table)

0 Kudos
4 Replies
JakeSkinner
Esri Esteemed Contributor

Hi Kristen,

The Make Table View tool only hide the fields, it doesn't actually delete them.  What I would recommend doing is adding the 'Table to Table' function to your script.  You can write the output to your scratch geodatabase, and then export to excel.

KristenE
New Contributor III

True it only hides the fields, but then when I export to Excel shouldn't it only export the fields that are in the table view?

The end goal is to get to an Excel table. I could use the table to table tool and field mappings or copy the feature class and delete fields before exporting, but I was trying bypass making a new GIS file before exporting to Excel.

0 Kudos
JakeSkinner
Esri Esteemed Contributor

Unfortunately, hidden fields are still exported.  One advantage of writing the output from the Table to Table tool to the scratch geodatabase is that it will make your tool portable, because this location will always be available or created at execution time.

DanPatterson_Retired
MVP Emeritus

You could also roll out your own using numpy there are tools for converting numpy arrays to tables and tables to numpy arrays .... you then have complete control.

0 Kudos