0
同行,使用Python将数据从Excel导入Oracle表格
新手在这里。有没有一种方法可以从excel文件读取数据并加载到Oracle表中?一些示例python脚本会有很大的帮助。我做了几行代码来熟悉,如下所示。
P.S.编辑:我的意思是这只是我的部分代码。我不确定如何在Oracle部分中将'insert statement'或'create table'语句作为此代码的一部分。我想加载数据,因为它从excel中读取每个列的循环。 TIA!
import openpyxl
import cx_Oracle
#Oracle connection starts here
connection = cx_Oracle.connect("<schema>", "<pwd>", "<hostname>/<sid/service>")
print("Database version:", connection.version)
print(cx_Oracle.version)
print(connection.current_schema)
# creating a table
create_table = """
CREATE TABLE test (
col1 VARCHAR2(50) NOT NULL,
col2 VARCHAR2(50) NOT NULL,
col3 VARCHAR2(50) NOT NULL,
col4 VARCHAR2(50) NOT NULL,
col5 VARCHAR2(50) NOT NULL,
col6 VARCHAR2(50) NOT NULL,
col7 VARCHAR2(50) NOT NULL
)
"""
from sys import modules
cursor.execute(create_table)
from openpyxl import Workbook
wb = openpyxl.load_workbook('<name of the file>',data_only=True)
ws = wb['Sheet1']
x=1
m=1
# looping through each column
for j in range(2,ws.max_column+1):
ID = m
col1 = ws.cell(row=x,column=j).value
m = m+1
col2 = ws.cell(row=1, column=j).value
col3 = ws.cell(row=2, column=j).value
col4 = ws.cell(row=3,column=j).value
col5 = ws.cell(row=4, column=j).value
col6 = ws.cell(row=5, column=j).value
col7 = ws.cell(row=6, column=j).value
#looping through each row for each column
for i in range(1,ws.max_row+1):
Cellval= ws.cell(row=i, column=j).value
# Inserting all the above variables for each column loop
insert_table="""
INSERT INTO test (col1,col2,col3,col4,col5,col6,col7)
VALUES ("""+col1+""",
"""+col2+""",
"""+col3+""",
"""+col4+""",
"""+col5+""",
"""+col6+""",
"""+col7+""")"""
cursor.execute(insert_table)
x=x+1
connection.close()
我是对的吗?
有用吗?如果没有,出了什么问题? –
我的意思是这只是我的部分代码。我不确定如何在Oracle部分中将'insert statement'或'create table'语句作为此代码的一部分。我想加载数据,因为它从excel中读取每个列的循环。 TIA! – Adi
创建您的表格并将表格的结构添加到上面的表格中。然后,您可以在for循环中执行插入语句,并使用execute来执行预制,或将其放入数组并使用execute_many。请参阅cx_oracle文档以获取相关帮助。 –