I am able to reproduce your issue on ArcGIS 10.4.1. This issue can be reproduced using any other field, so it's not OBJECTID
specific. My guess is that because you hide a field when creating a table view, it might get misinterpreted by the Table To Excel
tool and it gets an empty string internally. There are a couple of workarounds:
Using external xlsxwriter
package
I use xlsxwriter
Python package for all my Excel-generation related operations. It's much more flexible than the Table To Excel
because it uses .xlsx
Excel files:
- Number of columns: Table To Excel: 256; xlsxwriter: 16,384
- Number of rows: Table To Excel: 65,536; xlsxwriter: 1,048,576
You can create own styles for cells using xlsxwriter
, add charts, formulas and many other things. The reason Esri is using the xlwt
for the Table To Excel tool is most likely because this package comes built-in into the Python installation. Some of the functionality I mention is also possible to implement using xlwt
but it's a lot of work comparing to xlsxwriter
.
You can use the arcpy.da.SearchCursor
for iterating rows as you need and write rows to Excel. Maybe you would like to use another columns order or add some borders. In a word, make a transition to xlsxwriter
whenever you can.
This is everything it takes to export the rows from a feature class using a where_clause
:
import xlsxwriter
import arcpy
excel_path = r'C:\GIS\out_fc.xlsx'
workbook = xlsxwriter.Workbook(excel_path)
worksheet = workbook.add_worksheet()
fc = r"C:\GIS\Temp\ArcGISHomeFolder\Default.gdb\cities"
fields = [f.name for f in arcpy.ListFields(fc) if not f.required]
rows = [r for r in arcpy.da.SearchCursor(fc, fields, 'POP1990 > 1000000')]
rows_structured = [list(elem) for elem in rows]
rows_structured.insert(0, fields)
for i, row in enumerate(rows_structured):
worksheet.write_row(i, 0, row)
workbook.close()
Using the built-in xlwt
module
However, if you do need to use the xlwt
built-in module, you may like running the Table To Excel
Python module on your own to work around the problem with hiding fields. If you print sys.path
after importing the arcpy
, you will see that there is a path to 'C:\\Program Files (x86)\\ArcGIS\\Desktop10.4\\ArcToolBox\\Scripts'
.
The Table To Excel
geoprocessing tool is just a plain Python module stored there as TableToExcel.py
. You can just import this file and then call the function to generate the Excel. I am able to create an output Excel .xls
file without OBJECTID
using the table view obtained from the Make Table View
GP tool.
import arcpy
import TableToExcel
arcpy.MakeTableView_management(in_table="Database Connections/esrigdb.sde/esrigdb.DBO.Property",
out_view="DBO.Property_View",
where_clause="", workspace="", field_info="""OBJECTID OBJECTID HIDDEN NONE""")
TableToExcel.table_to_excel(in_table="DBO.Property_View", output=r'C:\GIS\Temp\outHiddenObjId.xls',
use_domain_desc=True,use_field_alias=True)