28、python3.7(windows)将ORACLE11gR2中的数据取出写入excel表

28.1、下载python的离线扩展模块:

1、windows下python的离线扩展模块下载地址为:

https://www.lfd.uci.edu/~gohlke/pythonlibs/

提示:

可以通过python官方的pypi仓库下载linux或windows相应python版本的离线扩展模块:https://pypi.org/


2、下载连接oracle的python离线扩展模块:


3、下载操作excel表的python离线扩展模块:


28.2、安装下载的python离线扩展模块:

1、以管理员的方式运行cmd,进入windows的dos界面,并进入离线python模块所在的目录。


2、安装:

pip isntall cx_Oracle-7.3.0-cp37-cp37m-win_amd64.whl

pip isntall xlrd-1.2.0-py2.py3-none-any.whl

pip isntall xlutils-2.0.0-py2.py3-none-any.whl

pip isntall xlwt-1.3.0-py2.py3-none-any.whl


28.3、安装Oracle客户端:

1、下载oralce11gR2客户端:

下载地址为:https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html

(1)下载的版本如下(亲测该版本适用于oralce11gR2和oracle10g):


(2)解压该文件,我将其放在C:\Program Files (x86)\目录下。


2、添加环境变量:


3、把oracle客户端的安装文件中以".dll"结尾的文件复制到python的安装目录中:

(1)


(2)


28.4、python代码实现:

# -*- coding: utf-8 -*-

import sys

# 读取excel

import xlrd

# 写入excel

import xlwt

# 操作 Excel 文件的实用工具,如复制、分割、筛选等

from xlutils.copy import copy

# oralc模块

import cx_Oracle as oracle

# 时间模块

import datetime


# 连接数据库的url地址

oracle_url = "net/[email protected]:1521/orcl"

# 输入文件路劲,文件必须存在

file_in_path = "lc.xls"

# 输出文件路径,自动创建文件,如果文件已存在则自动覆盖

file_out_path = "chang.xls"

# excel的sheet表名

sheet_name = "Sheet1"



# 输出显示内容

class Logger(object):

def __init__(self, filename='default.log', stream=sys.stdout):

self.terminal = stream

# 如果没有就新生成一个文件,存在就覆盖

self.log = open(filename, 'w', encoding="utf-8")


def write(self, message):

self.terminal.write(message)

self.log.write(message)


def flush(self):

pass



# 获取当前时间

now_time = datetime.datetime.now().strftime('%Y-%m-%d')

# 将正常日志和错误日志分别写入到两个文件中

sys.stdout = Logger(now_time + '-normal.log', sys.stdout)

sys.stderr = Logger(now_time + '-error.log', sys.stderr)


try:

# 数据库连接

db = oracle.connect(oracle_url)

# 创建cursor

cursor = db.cursor()

# 打开已存在的表

oldWb = xlrd.open_workbook(file_in_path, formatting_info=True)

# 复制

newWb = copy(oldWb)

# 取sheet表

newWs = newWb.get_sheet(sheet_name)



# 执行sql语句

def exec_sql(sql):

return cursor.execute(sql).fetchall()



# 在excel表中插入数据

def insert_excel(row, col, value):

# 写入数据

newWs.write(row, col, value)



# sql语句

sql = "select * from bhl_user"

# 从数据库中取出的数据

value = exec_sql(sql)[0][1]

# 将取出的数据插入到excel表中第几行第几列,表格的坐标是从0开始计算的

insert_excel(2, 4, value)


print("insert into data success!")

except Exception as msg:

print(msg)

print("insert into data faild!")


# 关闭数据库连接

db.close()

# 保存文件

newWb.save(file_out_path)























猜你喜欢

转载自www.cnblogs.com/LiuChang-blog/p/12709949.html