import arcpy
inputTable = arcpy.GetParameter(0)
#When running in the python window in ArcMap, I comment out line 3 above and un-comment line 6.
#inputTable = "C:\\Users\\user1\\Desktop\\example.csv"
arcpy.MakeXYEventLayer_management(inputTable, "Longitude", "Latitude", "tableXY")
arcpy.FeatureClassToFeatureClass_conversion("tableXY", "%scratchfolder%\\Scratch.gdb\\", "tableXYfc")
arcpy.SpatialJoin_analysis("%scratchfolder%\\Scratch.gdb\\tableXYfc", "Database Connections\\example.sde\\example.polygons", "in_memory\\_join","","")
arcpy.TableToExcel_conversion("in_memory\\_join", "C:\\Users\\user1\\Desktop\\final_export.xls")
Here's the script which (which works perfectly in ArcMap).