简体   繁体   中英

Python: how to read the data from the oracle, and then write to Excel

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

Install database driver for connecting to the db and pandas to streamline the excel writing and data manipulations.

$ pip install cx_Oracle pandas

in your script do something like this:

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

this answer is come from: 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)

Thanks to Robin Nemeth for his answer. I made a little modification to it and got the required output.

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

Here, data.to_excel() should be called before closing the connection, else will result in the following error "DatabaseError: DPI-1040: LOB was already closed".

Even removed the data.head() function, which didn't affect my output.

import cx_Oracle

import pandas as pd

import xlsxwriter

con = cx_Oracle.connect('user/password@IP:port/service_name')

with pd.ExcelWriter("", engine="xlsxwriter", options = {'strings_to_numbers': True, 'strings_to_formulas': False}) as writer:

                try:

                    df = pd.read_sql("SELECT * FROM myTABLE", con)

                    df.to_excel(writer, sheet_name = "Sheet1", header = True, index = False)

                    print("File saved successfully!")

                    row = len(df.axes[0])

                except:

                    print("There is an error")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM