How to export a table to csv or excel format

血红的双手。 提交于 2021-01-02 05:25:15

问题


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

回答1:


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!




回答2:


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




回答3:


For a non-python solution, Tom Kyte has some excellent scripts for generating CSV files using PL/SQL (UTL_FILE), SQL*Plus, and Pro*C.



来源:https://stackoverflow.com/questions/5669773/how-to-export-a-table-to-csv-or-excel-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!