oaolfa

Convert a GDB into excel with python script

Discussion created by oaolfa on Apr 18, 2017
Latest reply on Apr 18, 2017 by rvburton

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))

Outcomes