Select to view content in your preferred language

Convert a GDB into excel with python script

4322
1
04-18-2017 10:50 AM
olfaabid
Deactivated User

How can I convert the hole EMPTY tables of a GDB into excel file with separate sheets using Python. I have been straggling for at least 4 days! Thank you everyone. 

Here is my Python code : 

import arcpy
import os
#import domainvalues
# Set environment settings
arcpy.env.workspace = "D:\Documents\abid\Travail\_RDC\_BDD"
# Set local variables
dataset = "D:\Documents\abid\Travail\_RDC\_BDD\GEOL_GDB.gdb"
output = "D:\Documents\abid\Travail\_RDC\_BDD\EXCEL"

def export_to_xls(dataset, output):

arcpy.AddMessage("Reading Table...")
#header, rows = header_and_iterator(dataset)
arcpy.AddMessage("Writing Excel File...")
def _xls():
try:
import xlwt
except ImportError:
arcpy.AddError("Import of xlwt module failed.\nThe XLWT module can\
be downloaded from: http://pypi.python.org/pypi/xlwt")
return
# Make spreadsheet
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(os.path.split(dataset)[1])
#Set up header row, freeze panes
header_style = xlwt.easyxf("font: bold on; align: horiz center")
for index, colheader in enumerate(header):
worksheet.write(0, index, colheader.replace(".", "_"))
worksheet.set_panes_frozen(True)
worksheet.set_horz_split_pos(1)
worksheet.set_remove_splits(True)
# Write rows
for rowidx, row in enumerate(rows):
for colindex, col in enumerate(row):
worksheet.write(rowidx + 1, colindex, col)
# All done
workbook.save(output)
def _xlsx():
try:
import openpyxl
except ImportError:
arcpy.AddError("Import of module failed.\nThe OPENPYXL module can\
be downloaded from: http://pypi.python.org/pypi/openpyxl")
return
# create spreadsheet
wb = openpyxl.Workbook(optimized_write=True)
ws = wb.create_sheet()
# insert the header row
ws.append(header)
# write rows
for row in rows:
ws.append(row)
# All done
wb.save(output)a
if output.endswith('.xls'):
rowcount = int(arcpy.GetCount_management(dataset).getOutput(0))
if rowcount <= 65535 and len(header) <= 255:
_xls()
else:
arcpy.AddError('Table too large to export to .xls.\
Select .xlsx output for tables larger than 256 fields x 65535 rows.')
else:
_xlsx()
if __name__ == "__main__":
dataset_name = arcpy.GetParameterAsText(0)
output_file = arcpy.GetParameterAsText(1)
try:
export_to_xls(dataset_name, output_file)
except Exception as err:
arcpy.AddError("Error: {0}".format(err))
0 Kudos
1 Reply
RandyBurton
MVP Alum

It helps to format your code when posting to Geonet; see Code Formatting... the basics++

I like to use arcpy's TableToExcel function.

# TableToExcel_conversion (Input_Table, Output_Excel_File, {Use_field_alias_as_column_header}, {Use_domain_and_subtype_description})
#   NAME/ALIAS  and  CODE/DESCRIPTION
arcpy.TableToExcel_conversion(featurename,xlsfile,"NAME","CODE")
arcpy.TableToExcel_conversion(featurename,xlsfile2,"ALIAS","DESCRIPTION")
0 Kudos