python用xlwings导出导入oracle数据库到excel

最近在学习python,又刚好有导出数据的需求,所以做了一下尝试,在知乎看过一些对比,觉得xlwing性能应该比较好,所以最后选择了xlwings来操作excel

导出数据

这里碰到一个问题,google查不到方案,最后选择了一个绕过的小技巧。

问题是:当数据库字段类型为字符时,且存的是"001301"类似于此类的编码,在用xlwings导出到excel时,前面的00会丢失。

解决办法:是针对该字段,查询语句前面在该字段加" ' ", 加了单引号后,excel自动默认该列为字符,这样前面的00就不会丢失

导出脚本:

ora-2-exl.py

# -*- coding: utf-8 -*-
import ora_conn
import sys
import xlwings as xw
import cx_Oracle
import datetime

def ora_to_excel():
    with open(sys.argv[1],'rb') as f:
        sql = f.read()
    cursor = ora_conn.connect.cursor()
    cursor.execute(sql)
    app = xw.App(visible=False)
    wb = xw.Book()
    sht = wb.sheets[0]
    #处理表头
    i = 0
    start = datetime.datetime.now()
    for col in cursor.description:
        i += 1
        sht.range((1,i)).value = col[0]
    
    #写入数据
    offset = 2
    while True:
        results = cursor.fetchmany(30000)
        if not results:
            break
        #对于数据库为字符串的'001',需要在查询的sql语句加上',否则前面的00在excel会丢失
        sht.range('A'+ str(offset)).options().value = results
        offset = offset + len(results)
    wb.save(sys.argv[2])
    wb.close()
    app.quit()
    cursor.close()
    ora_conn.connect.close()
    print(datetime.datetime.now() - start)
if __name__ == '__main__':
    ora_to_excel()

导入数据

这里碰到一个问题就是日期格式的问题,excel的日期格式最好是yyyy/mm/dd hh:mi:ss

exl-2-ora.py

# -*- coding: utf-8 -*-
import xlwings as xw
import ora_conn
import datetime
import sys

def exl_to_ora(table_name,file_name):
    app = xw.App(visible=False)
    wb = app.books.open(file_name)
    sht = wb.sheets[0]
    data = sht.range('A1').expand().value
    rows = len(data) - 1
    cols = data[0]
    
    cursor = ora_conn.connect.cursor()
    #处理插入的语句
    cols_str = '('
    for x in cols:
        cols_str = cols_str + str(x) + ','
    cols_str = cols_str.strip(',') + ')'
    
    values_str = ' values ('
    for i in range(len(cols)):
        values_str = values_str + ':' + str(i+1) + ','
    values_str = values_str.strip(',') + ')'
    
    offset = 1
    #print("insert into " + table_name + cols_str + values_str)
    try:
        start = datetime.datetime.now()
        while(offset < rows):
            cursor.executemany("insert into " + table_name + cols_str + values_str,data[offset:offset+20000])
            offset += 20000
            ora_conn.connect.commit()
            #print('commit data rows:'+ str(offset))
        
    finally:
        wb.close()
        app.quit()
        cursor.close()
        ora_conn.connect.close()
    print(datetime.datetime.now() - start )
    
if __name__ == '__main__':
    exl_to_ora(sys.argv[1],sys.argv[2])

ora_conn.py

import cx_Oracle
dbs = {
    'dev':'use1/[email protected]/dev',
    'test':'use1/[email protected]/test',
    'uat':'use1/[email protected]/uat'
}
connect = cx_Oracle.connect(dbs['dev'])
print('connect success')

你可能感兴趣的:(python用xlwings导出导入oracle数据库到excel)