參考資料:OpenPyXL的使用教程(一)
openpyxl 基本操作
from openpyxl import load_workbook, Workbook
# ========
# 新建工作簿+sheet
wb = Workbook() #guess_types=True
#
filepath = r'e:/aa.xlsx'
wb = load_workbook(filepath)
wb.save(filepath) #如果存在會覆蓋,as_template=True, 將文件保存為模板,默認False
# sheet名列表
#wb.get_sheet_names() #已棄用
wb.sheetnames
[sheet.title for sheet in wb]
# ========
# 新建sheet
ws = wb.create_sheet(0) #第一個位置
ws = wb.create_sheet(title='1', index=1)
ws.title = 'Sheet1'
# 訪問指定sheet
ws = wb.active #調用wb._active_sheet_index
#ws = wb.get_sheet_by_name(sheet_name) #已棄用
ws = wb['Sheet1']
ws.rows
ws.columns
#ws.sheet_properties.tabColor = "1072BA" #改變sheet標簽欄字體顏色
# 增刪改查
ws['A4'] = 4
ws.cell('A4')
c = ws.cell(row = 4, column = 2)
c.value = 4
cell_range = ws['A1':'C2']
#[cell.value for row in ws.iter_rows('A1:C2') for cell in row]
# ========
dataframe.to_excel(filepath, sheet_name=sheet_name, index=None)
writer = pd.ExcelWriter(filepath, engine='openpyxl')
dataframe.to_excel(excel_writer=writer, sheet_name=sheet_name, index=None)
writer.save()
writer.close()
# ========
def excelAddSheet(dataframe, filepath, sheet_name):
import os
from openpyxl import load_workbook, Workbook
#FileNotFoundError
if os.path.exists(filepath):
#當表名已存在時,后面還可以添加參數,進行追加
wb = load_workbook(filepath) #keep_vba=True
#sheet = book.active
with pd.ExcelWriter(filepath, engine='openpyxl') as writer:
writer.book = wb
#stratrow=1, startcol=1
dataframe.to_excel(excel_writer=writer, sheet_name=sheet_name, index=None)
#writer.save()
#writer.close()
else:
dataframe.to_excel(filepath, sheet_name=sheet_name, index=None)
oracle2Excel
import cx_Oracle
import openpyxl
# 用戶名
username = 'tj_20160217'
# 密碼
password = 'tj_20160217'
# IP
ip = '10.0.250.19'
# 端口
port = '1521'
# 數據庫實例名
servername = 'starbass'
# 獲取連接
xlsxPath = 'E:\\sysconfigen.xlsx'
sheetName = 'sysconfigen'
wb = openpyxl.Workbook()
ws = wb.active
ws.title = sheetName
with cx_Oracle.connect(username + '/' + password + '@' + ip + ':' + port + '/' + servername) as db:
cur = db.cursor()
result = cur.execute('select * from sysconfigen')
row = 1
column = 1
# 獲取表頭
for header in cur.description:
ws.cell(row, column).value = header[0]
column += 1
row += 1
for one_result in result.__iter__():
column = 1
for at in one_result:
if at:
ws.cell(row, column).value = at
else:
# 空值處理
ws.cell(row, column).value = 'null'
column += 1
row += 1
wb.save(xlsxPath)
參考資料:https://github.com/a18792721831/StudyPython/tree/master/helloExcel
