[GIS] Export selected fields in ArcGIS to Excel using Python

arcgis-10.2arcgis-desktopexcelfield-mappingpython

I'm am creating a script that will allow a user to add XY coordinates to a point layer, then export (along with any addition user selected fields) to Excel. I am getting stuck on the iteration of the selected fields and how to map them to prepare to export to Excel. I have a parameter that derives the field names from the input point layer and the user can tick each field they wish to include in the Excel export.

Best Answer

I found that I simply needed to split the field selections and then iterate through the list using field mapping.

paramInWells = arcpy.GetParameterAsText(0)
paramInFields = arcpy.GetParameterAsText(1)
paramInFieldList = paramInFields.split(";")
paramOutExcel = arcpy.GetParameterAsText(2)

arcpy.SetProgressorLabel("Processing...")
arcpy.AddMessage("\nAdding XY coordinates")

fms = arcpy.FieldMappings()
for field in paramInFieldList:
    fieldName = arcpy.FieldMap()
    fieldName.addInputField(paramInWells, field)
    fms.addFieldMap(fieldName)

arcpy.FeatureClassToFeatureClass_conversion(paramInWells, "in_memory", "XYCoords_Tmp", field_mapping=fms)

paramOutXyTemp = "in_memory\\XYCoords_Tmp"
arcpy.AddXY_management(paramOutXyTemp)
arcpy.AddMessage("\nCreating Excel document")
arcpy.TableToExcel_conversion(paramOutXyTemp, paramOutExcel)
Related Question