这里介绍使用python查询oracle保存为excel的两种方法,一种用openpyxl保存,另一种用pandas保存。
一、使用openpyxl保存。
1.导入第三方库
import cx_Oracle
import openpyxl
2.定义导出函数,sql语句为单独保存在同一个文件夹的sql文件,通过打开文件读取sql语句,不直接把sql语句写在代码里可让代码显得简洁,还可以不必处理sql语句的换行问题。在写入excel文件时要注意防止用科学计数法写入造成信息丢失,先转换为字符串再进行保存。
def export_excel(sql,fileName):
rr = curs.execute(sql)
rows = curs.fetchall()
#获取字段名
title = [ i[0] for i in curs.description ]
#创建excel表
wb = openpyxl.Workbook()
ws = wb.active
#插入字段名到第一行
for c in range(len(title)):
ws.cell(1,c+1,value = title[c])
#写入查询数据
for r in range(len(rows)):
for c in range(len(rows[r])):
if rows[r][c]: #值不为空时写入,空值不写入
ws.cell(r+2,c+1,value=str(rows[r][c])) #str()防止用科学计数法写入造成信息丢失
#保存sql脚本
ws1 = wb.create_sheet('sql')
ws1.cell(1,1,value=sql)
wb.save(fileName)
wb.close()
curs.close()
3.主代码,连接数据库conn = cx_Oracle.connect(‘user/password@IP/db’,encoding = ‘utf-8’) 时注意添加编码格式,否则无法显示中文。
if __name__ == '__main__':
conn = cx_Oracle.connect('user/password@IP/db',encoding = 'utf-8') #utf-8显示中文
curs= conn.cursor()
#打开sql文件获取sql语句
with open('查询语句.sql') as sql_0:
sql = sql_0.read()
export_excel(sql,'book1.xlsx')
conn.close()
二、使用pandas保存,这种方法相对简单点。
1.导入第三方库
import cx_Oracle
import openpyxl
import numpy as np
import pandas as pd
2.定义导出函数,在对科学计数问题的处理上和使用openpyxl不太相同,不能直接将所有列转为字符串类型,通过判断列类型为int类型再对该列转为str类型。
def export_excel(sql,fileName):
rr = curs.execute(sql)
rows = curs.fetchall()
#rows = curs.fetchmany(20)
#获取字段名
title = [ i[0] for i in curs.description ]
writer = pd.ExcelWriter(fileName)
df = pd.DataFrame(rows,columns = title)
#print(df.loc[:,'DJXH'].dtype)
"""#将int类型改为str类型,防止输出到excel变为科学计数法导致信息不完整,不能直接df = pd.DataFrame(rows,columns = title).astype(str),这样空值会在excel中保存为NaN等值。
for t in title:
if df.loc[:,t].dtype == 'uint64':
df.loc[:,t] = df.loc[:,t].astype(str)"""
#astype(str)转为str类型,空值将变为'nan'
df = df[df['登记序号'].isin(djxh)].astype(str)
#将'nan'值替换为空,这样在excel中空值不保存为nan
df = df.replace('nan', np.nan)
#保存结果
df.to_excel(writer,sheet_name = 'result',index = False)
df_sql = pd.DataFrame([sql])
df_sql.to_excel(writer,sheet_name = 'sql',index = False)
writer.save()
curs.close()
3.主代码,和使用openpyxl相同。
if __name__ == '__main__':
conn = cx_Oracle.connect('user/password@IP/db',encoding = 'utf-8') #utf-8显示中文
curs= conn.cursor()
#打开sql文件获取sql语句
with open('查询语句.sql') as sql_0:
sql = sql_0.read()
export_excel(sql,'book1.xlsx')
conn.close()