如何将表导出为csv或excel格式

Khw*_*ien 9 python cx-oracle oracle11g

我需要将oracle表导出为csv/excel文件格式(以及列标题).通过cx_oracle或通过sqlplus欢迎的解决方案.

评论中的Python代码:

con = cx.connect() 
cur = con.cursor() 
printer = cur.execute(sqlcode) 
con.commit() 
Run Code Online (Sandbox Code Playgroud)

jsw*_*jsw 12

也许使用csv模块(来自标准库):

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())
Run Code Online (Sandbox Code Playgroud)

如果您有大量数据,请将fetchall()展开到循环中.

快乐的小道!

  • 始终在二进制模式下使用Python2打开csv文件.使用Python3,使用`newline =''`. (3认同)