Python使用openpyxl导出Oracle中指定表数据到Excel

1、使用openpyxl库导出oracle中表数据需要知道的相关概念

1)、工作薄

Workbook是Excel工作薄的抽象,这个可以通过wb = openpyxl.Workbook()来创建

2)、工作表

Worksheet是表格的抽象,一个工作薄下可以有过多个工作表,可以通过ws = wb[‘Sheet’]来创建,也可以通过ws = wb.create_sheet(title=‘new sheet’)来创建,新创建的工作薄下有个名为Sheet的工作表

3)、单元格

Cell,是单元格的抽象,通过row,col坐标来确定单元格Cell的位置。

2 、创建脚本读取并写入数据到Excel

import cx_Oracle
import openpyxl

conn = cx_Oracle.connect('scott/scott@TNS_LISSEN')
cursor = conn.cursor()

cursor.execute("select * from emp")
results = cursor.fetchall()

#获取标题信息
descriptions = cursor.description

#将表中标题保存到列表titleEmp
titleEmp = []
for desc in descriptions:
    titleEmp.append(desc[0])

wb = openpyxl.Workbook()
ws = wb['Sheet']

#将标题内容写入到Excel中
for colIndex in range(1,len(titleEmp) + 1):
    ws.cell(row=1,column=colIndex).value = titleEmp[colIndex - 1]

#将查询到的表中数据写入到Excel中
for rowIndex in range(2,len(results)+2):
    for colIndex in range(1,len(titleEmp)+1):
       ws.cell(row=rowIndex,column=colIndex).value = results[rowIndex - 2][colIndex - 1]
wb.save('emp.xlsx')

cursor.close()
conn.close()

3、检查导出结果

导出后Excel中数据:
在这里插入图片描述
Oracle中scott.emp表数据:

SCOTT@lissen>select * from emp;

     EMPNO ENAME      JOB               MGR HIREDATE              SAL       COMM     DEPTNO
---------- ---------- ---------- ---------- -------------- ---------- ---------- ----------
      7369 SMITH      CLERK            7902 17-12-80            800                    20
      7499 ALLEN      SALESMAN         7698 20-2-81           1600        300         30
      7521 WARD       SALESMAN         7698 22-2-81           1250        500         30
      7566 JONES      MANAGER          7839 02-4-81           2975                    20
      7654 MARTIN     SALESMAN         7698 28-9-81           1250       1400         30
      7698 BLAKE      MANAGER          7839 01-5-81           2850                    30
      7782 CLARK      MANAGER          7839 09-6-81           2450                    10
      7788 SCOTT      ANALYST          7566 19-4-87           3000                    20
      7839 KING       PRESIDENT             17-11-81           5000                    10
      7844 TURNER     SALESMAN         7698 08-9-81           1500          0         30
      7876 ADAMS      CLERK            7788 23-5-87           1100                    20
      7900 JAMES      CLERK            7698 03-12-81            950                    30
      7902 FORD       ANALYST          7566 03-12-81           3000                    20
      7934 MILLER     CLERK            7782 23-1-82           1300                    10

已选择14行。

可以通过此方法来巡检数据库表空间使用情况然后导出到Excel。

发布了20 篇原创文章 · 获赞 24 · 访问量 2591

猜你喜欢

转载自blog.csdn.net/u011285708/article/details/104126877