Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a table to csv or excel format

I need to export a oracle table to a csv/excel file format (along with the column headings). A solution through cx_oracle or through sqlplus welcome.

Python code from the comment:

con = cx.connect() 
cur = con.cursor() 
printer = cur.execute(sqlcode) 
con.commit() 
like image 733
Khwaishien Avatar asked Apr 14 '11 21:04

Khwaishien


2 Answers

perhaps use csv module (from standard library):

import csv
cursor = connection.cursor() # assuming you know how to connect to your oracle db
cursor.execute('select * from table_you_want_to_turn_to_csv')
with open('output_file.csv', 'wb') as fout:
    writer = csv.writer(fout)
    writer.writerow([ i[0] for i in cursor.description ]) # heading row
    writer.writerows(cursor.fetchall())

If you have loads of data, unroll the fetchall() into a loop.

Happy trails!

like image 169
jsw Avatar answered Oct 07 '22 12:10

jsw


to create XLS file, use xlwt module from the python-excel project.

like image 31
Michał Šrajer Avatar answered Oct 07 '22 12:10

Michał Šrajer