python将oracle查询的数据保存到excel

参考网上。
https://blog.csdn.net/bin083/article/details/95088389

import cx_Oracle
import openpyxl
import time

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

if __name__ == '__main__':
    conn = cx_Oracle.connect('chhq/[email protected]/TOPTEST',encoding = 'utf-8') #utf-8显示中文
    curs= conn.cursor()
    #打开sql文件获取sql语句
    with open('查询语句.sql') as sql_0:
        sql = sql_0.read()
    cur_date = time.strftime("%Y-%m-%d-%H%M%S", time.localtime())
    export_excel(sql,cur_date+'.xlsx')
    conn.close()

猜你喜欢

转载自blog.csdn.net/yemenlinweihan/article/details/104021563