10

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

来自评论的 Python 代码:

con = cx.connect() 
cur = con.cursor() 
printer = cur.execute(sqlcode) 
con.commit() 
4

3 回答 3

14

也许使用 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())

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

快乐的小径!

于 2011-04-15T02:01:58.170 回答
2

要创建 XLS 文件,请使用python-excel项目中的 xlwt 模块。

于 2011-04-14T21:36:09.760 回答
1

对于非 Python 解决方案,Tom Kyte 提供了一些出色的脚本,用于使用 PL/SQL (UTL_FILE)、SQL*Plus 和 Pro*C生成 CSV 文件。

于 2011-04-15T03:36:44.900 回答