【发布时间】:2017-10-13 05:56:33
【问题描述】:
Python:如何从oracle中读取数据,然后写入Excel,Excel部分列可以只读?
【问题讨论】:
Python:如何从oracle中读取数据,然后写入Excel,Excel部分列可以只读?
【问题讨论】:
安装database driver 用于连接数据库和pandas 以简化excel 写入和数据操作。
$ pip install cx_Oracle pandas
在你的脚本中做这样的事情:
import cx_Oracle
con = cx_Oracle.connect('user/password@dsn')
data = pd.read_sql('SELECT * FROM mytable', con)
con.close()
data.head() # take a peek at data
data.to_excel('my_oracle_table.xlsx')
【讨论】:
这个答案来自: Python xlwt - making a column readonly (cell protect)
from xlwt import Workbook, Worksheet, easyxf
# ...
# Protect worksheet - all cells will be read-only by default
my_worksheet.protect = True # defaults to False
my_worksheet.password = "something_difficult_to_guess"
# Create cell styles for both read-only and editable cells
editable = easyxf("protection: cell_locked false;")
read_only = easyxf("") # "cell_locked true" is default
# Apply your new styles when writing cells
my_worksheet.write(0, 0, "Can't touch this!", read_only)
my_worksheet.write(2, 2, "Erase me :)", editable)
【讨论】:
感谢 Robin Nemeth 的回答。我对其进行了一些修改,得到了所需的输出。
import cx_Oracle
con = cx_Oracle.connect('user/password@dsn')
data = pd.read_sql('SELECT * FROM mytable', con)
data.to_excel('my_oracle_table.xlsx') #called before closing the connection
con.close()
这里,data.to_excel() 应该在关闭连接之前调用,否则会导致如下错误“DatabaseError: DPI-1040: LOB was already closed”。
甚至删除了 data.head() 函数,这并没有影响我的输出。
【讨论】: