使用openpyxl库将查到的数据转为Excel(.xlsx格式),并试着用自定义的Excel类将生成Excel的步骤封装,这样只要给固定的数据格式,就不用关心Excel的具体生成了。
import logging
from openpyxl import Workbook, load_workbook
from openpyxl.styles import *
class Excel:
@description :
@Author : admin
@Time : 2022-04-08 15:37
def __init__(self):
self.character_list = [
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
self.column_list = [
[item for item in self.character_list],
['A' + item for item in self.character_list],
['B' + item for item in self.character_list],
def run(self, result, full_file_name):
@description :
@Author : admin
@Time : 2022-04-08 15:37
row = 1
try:
wb1 = load_workbook(full_file_name)
ws1 = wb1['数据']
except Exception as e:
logging.warning(e)
wb1 = Workbook()
ws1 = wb1['Sheet']
ws1.title = '数据'
index = 0
for item in result['title']:
i = int(index / 26)
j = index % 26
cell_pos = self.column_list[i][j] + str(row)
ws1[cell_pos] = item[0]
ws1[cell_pos].font = Font(bold=True)
ws1.column_dimensions[self.column_list[i][j]].width = 15
index += 1
row += 1
for data_list in result['data']:
index = 0
for item in data_list:
i = int(index / 26)
j = index % 26
ws1[self.column_list[i][j] + str(row)] = item
index += 1
row += 1
wb1.save(full_file_name)
注: run()中result数据格式为=> “2.条件查询” 中格式
将oracle数据库查询结果导出为excel
在工作中遇到需要批量将oracle查询结果导出为excel的需求,正好在自学python,于是用python写了一个小的脚本完成这个功能。在这里放出来供大家参考指正。
这里的cx_Oracle 如果没有需要安装
import pandas as pd
import cx_Oracle
#oracle数据库用户名
name='bzXXXX'
#数据库密码
pwd='XXXX'
#数据库ip和实例名
tes = '127.0.0.1/orcl'
#创建连接
由于是Python实现的,所以需要有Python环境的支持
Python2.7.11
我的Python环境是2.7.11。虽然你用的可能是3.5版本,但是思想是一致的。
pip install xlwt
MySQLdb
pip install MySQLdb
如果上述方式不成功的话,可以到sourceforge官网上去下载windows上的msi版本或者使用源码自行编译。
数据库相关
本次试验,数据库相关的其实也就是如何使用Py
这里介绍使用python查询oracle保存为excel的两种方法,一种用openpyxl保存,另一种用pandas保存。
一、使用openpyxl保存。
1.导入第三方库
import cx_Oracle
import openpyxl
2.定义导出函数,sql语句为单独保存在同一个文件夹的sql文件,通过打开文件读取sql语句,不直接把sql语句写在代码里可让代码显得简洁,还可以不必处理sq...