Select to view content in your preferred language

Is it possible to export data from SDE using python?

3053
4
Jump to solution
12-05-2016 11:20 AM
ScottMcGee1
Deactivated User

I'd like to save the end user numerous steps to export data saved in the SDE database.  Right now they export the data as a shapefile, open the DBF in excel and save that to CSV so they can use the mail merge function in Word to populate inspection forms.

0 Kudos
1 Solution

Accepted Solutions
ChristianWells
Esri Regular Contributor

Here is a sample of what I was talking about above. Let me know if you have any questions on this.

import arcpy, csv

#SDE Feature Class
fc = r"Database Connections\sdefile.sde\SDE.us_cities"

#Open CSV file
csvfile = open(r'c:\tmp\us_cities.csv', 'wb')

#Create CSV Writer
csvwriter = csv.writer(csvfile)

#Write header to CSV file
csvwriter.writerow(['FID', 'CITY_FIPS', 'CITY_NAME', 'STATE_NAME'])

#Loop through SDE FC and collect specific fields
for row in arcpy.da.SearchCursor(fc, ['OID@', 'CITY_FIPS', 'CITY_NAME', 'STATE_NAME']):
    #Write rows to CSV based on SearchCursor results
    csvwriter.writerow([row[0], row[1], row[2], row[3]])‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

4 Replies
ChristianWells
Esri Regular Contributor

Hi Scott, this should be relatively easy using arcpy.da.SearchCursor and csv.writer. If you create the cursor to search the rows, you can simply append them to a CSV. The nice thing about this is that you can open a writer object for CSV then iterate over the rows of the SDE table to read the row.

SearchCursor—Data Access module | ArcGIS for Desktop 

13.1. csv — CSV File Reading and Writing — Python 2.7.13 documentation 

ChristianWells
Esri Regular Contributor

Here is a sample of what I was talking about above. Let me know if you have any questions on this.

import arcpy, csv

#SDE Feature Class
fc = r"Database Connections\sdefile.sde\SDE.us_cities"

#Open CSV file
csvfile = open(r'c:\tmp\us_cities.csv', 'wb')

#Create CSV Writer
csvwriter = csv.writer(csvfile)

#Write header to CSV file
csvwriter.writerow(['FID', 'CITY_FIPS', 'CITY_NAME', 'STATE_NAME'])

#Loop through SDE FC and collect specific fields
for row in arcpy.da.SearchCursor(fc, ['OID@', 'CITY_FIPS', 'CITY_NAME', 'STATE_NAME']):
    #Write rows to CSV based on SearchCursor results
    csvwriter.writerow([row[0], row[1], row[2], row[3]])‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
DanPatterson_Retired
MVP Emeritus

at least one step simplified if you don't need geometry Excel To Table—Help | ArcGIS for Desktop 

0 Kudos
ScottMcGee1
Deactivated User

Thanks Christian, I think that is exactly what I'm looking for. Appreciate the help and the example.