Python:如何从oracle中读取数据,然后写入Excel

问题描述 投票:0回答:4

Python:如何从oracle中读取数据,然后写入Excel,Excel部分列只能读取?

python excel oracle
4个回答
1
投票

安装数据库驱动程序用于连接数据库和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')

0
投票

这个答案来自: Python xlwt - 使列只读(单元格保护)

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)

0
投票

感谢 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 close”。

甚至删除了 data.head() 函数,这并没有影响我的输出。


0
投票

导入cx_Oracle
将 pandas 导入为 pd
导入xlsxwriter
con = cx_Oracle.connect('用户/密码@IP:端口/服务名称')
使用 pd.ExcelWriter("", engine="xlsxwriter", options = {'strings_to_numbers': True, 'strings_to_formulas': False}) 作为编写者:

            try:

                df = pd.read_sql("SELECT * FROM myTABLE", con)    
                df.to_excel(writer, sheet_name = "Sheet1", header = True, index = False)    
                print("File saved successfully!")

            except:

                print("There is an error")
© www.soinside.com 2019 - 2024. All rights reserved.