openpyxl 是一个 用于读写Excel 2010 xlsx/xlsm/xltx/xltm 文件的Python库,最初是基于PHPExcel。
可以通过pip安装
pip install openpyxl
官方文档:https://openpyxl.readthedocs.io/en/stable/
源码地址:https://foss.heptapod.net/openpyxl/openpyxl
通过 load_workbook加载文件
def load_workbook(filename, read_only=False, keep_vba=KEEP_VBA,
data_only=False, keep_links=True):
import openpyxl
wb = openpyxl.load_workbook("示例.xlsx")
valueWb = openpyxl.load_workbook("示例.xlsx", data_only = True)
wb.save('修改后.xlsx')
names = ['Sheet', 'Sheet1', 'Sheet2']
for n in names:
wb.create_sheet(n)
# 创建Sheet,插入第一个位置
wb.create_sheet('Sheet3', 0)
# 单个Sheet
ws = wb['Sheet']
ws = wb[0]
# 所有Sheet
wb.worksheets
# 所有Sheet名字
wb.sheetnames
# 遍历所有Sheet
for sheet in wb:
print(sheet)
# Sheet标题
ws.title
ws=wb['Sheet2']
wb.move_sheet(ws, -1)
ws=wb['Sheet1']
wb.remove(ws)
del wb['Sheet']
# 在第1行前插入2行
ws.insert_rows(1, 2)
# 在第1列前插入2列
ws.insert_cols(1, 2)
# 增加一行
ws.append([1, 2, 3])
# 从第6行开始,往下删除3行
ws.delete_rows(6, 3)
# 删除第6列
ws.delete_cols(6)
cell = ws[A1]
ws.cell(row=1, column=1)
# 获取单元格值
cell.value
# 获取单元格坐标A1
cell.coordinate
# 按行遍历
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
for cell in row:
print(cell)
# 按列遍历
for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
for cell in col:
print(cell)
# 遍历范围单元格
cellRange=ws['A1:B3']
for row in cellRange:
for cell in row:
print(cell.value)
# 范围单元格
cellRange=ws['A1:B3']
# 单元格行
a=ws[1]
b=ws[5:10]
# 单元格列
c=ws['A']
d=ws['C:D']
ws['A1'] = 12
ws.cell(row=1, column=1, value = 12)
ws.merge_cells('A2:D2')
ws.unmerge_cells('A2:D2')
ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
cell.data_type
cell.number_format
具体默认内建样式可以见源码:https://foss.heptapod.net/openpyxl/openpyxl/-/blob/branch/3.0/openpyxl/styles/builtins.py
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
font = Font(name='Calibri',
size=11,
bold=False,
italic=False,
vertAlign=None,
underline='none',
strike=False,
color='FF000000')
cell.font = font
fill = PatternFill(fill_type=None,
start_color='FFFFFFFF',
end_color='FF000000')
cell.fill = fill
border = Border(left=Side(border_style=None,
color='FF000000'),
right=Side(border_style=None,
color='FF000000'),
top=Side(border_style=None,
color='FF000000'),
bottom=Side(border_style=None,
color='FF000000'),
diagonal=Side(border_style=None,
color='FF000000'),
diagonal_direction=0,
outline=Side(border_style=None,
color='FF000000'),
vertical=Side(border_style=None,
color='FF000000'),
horizontal=Side(border_style=None,
color='FF000000')
)
cell.border = border
alignment=Alignment(horizontal='general',
vertical='bottom',
text_rotation=0,
wrap_text=False,
shrink_to_fit=False,
indent=0)
cell.alignment = alignment
见文档:https://openpyxl.readthedocs.io/en/stable/styles.html#using-builtin-styles