素材、笔记文档下载
Windows用户打开命令行输入:pip install openpyxl
Mac用户打开终端/Terminal输入:pip3 install openpyxl
from openpyxl import Workbook # 引入openpyxl模块,可以创建xls或者xlsx文件
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = '表格1'
workbook.save(filename='写入表格.xlsx')
create_sheet()方法返回一个新的表格对象
index和title参数,指定新工作表的索引及名称
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
# 使用工作簿对象创建一个新的表格,表格名称为表格2
workbook.create_sheet(index=None,title='表格2')
print(workbook.sheetnames)
index
:整数类型,设置新工作表索引,默认为None即放在最后,如果设置为0,则表格放置在最前。
title
:字符串类型,设置新工作表名称,如果新工作表名称已存在,新工作表名称会自动变为title1。
remove()方法中接收一个表格对象而不是表格名称的字符串。需要具象化表名。
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook['表格2']
workbook.remove(sheet)
# workbook.remove(workbook['表格2'])
print(workbook.sheetnames)
workbook.save(filename='写入表格.xlsx')
workbook.copy_worksheet(sheet)
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet = workbook['表格1']
workbook.copy_worksheet(sheet)
print(workbook.sheetnames)
workbook.save(filename='写入表格.xlsx')
sheet.title = ‘工作表名’
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet = workbook['表格1 Copy']
sheet.title = '表格3'
print(workbook.sheetnames)
workbook.save(filename='写入表格.xlsx')
openpyxl.load_workbook()方法可以接收多个参数进行读取
from openpyxl import load_workbook
wb = openpyxl.load_workbook(filename='写入表格.xlsx', read_only=False, keep_vba=False, data_only=False, keep_links=True)
print(wb.sheetnames)
filename
:字符串类型,读取Excel文件的文件路径,可使用相对路径或是绝对路径。
read_only
:布尔类型,选择只读模式或是读写模式,若想写入公式及重新获取结果,需要用将这个模式关闭。默认为False。
keep_vba
:布尔类型,保留vba内容(这并不意味着可以使用它),默认为False。
data_only
:布尔类型,如果设置为True则包含公式的单元格,显示最近计算结果或是None,如果设置为False 则单元格显示公式,默认为False。
keep_links
:布尔类型,是否保留指向外部工作簿的链接。默认为True。
load_workbook(filename=“表格文件路径”) #若是绝对路径直接写文件名。
sheetnames属性可以取得工作簿中所有表名,返回为一个列表。
from openpyxl import load_workbook
fileName = "写入表格.xlsx"
wb = load_workbook(filename = fileName)
print(wb.sheetnames)
sheet = wb.active # 获取工作簿中的当前活动表
sheet = wb[‘工作表名称’] # 通过工作表名称选中的工作表
sheet.title # 获取活动表的表名称
# 获取上次关闭表格前激活的表格名称
from openpyxl import load_workbook
fileName = "写入表格.xlsx"
wb = load_workbook(filename = fileName)
sheet = wb.active
print(sheet.title)
# 获取特定表的表名称
from openpyxl import load_workbook
fileName = "写入表格.xlsx"
wb = load_workbook(filename = fileName)
sheet = wb['Sheet2']
print(sheet.title)
获取表格:workbook[sheet名称]
获取表格的尺寸大小:sheet.dimensions(表格存在数据的大小)
单独获取最大行:sheet.max_row
单独获取最大列:sheet.max_column
from openpyxl import load_workbook
workbook = load_workbook(filename="46
sheet = workbook['Booklist 12-26']
print("表格范围是:",sheet.dimensions)
print("最大行数是:", sheet.max_row)
print("最大列数是:", sheet.max_column)
输出结果:
表格范围是: A1:E4693
最大行数是: 4693
最大列数是: 5
.row 行数
.column 列数
.coordinate 坐标
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
cell = sheet['A5']
print("单元格的行号:",cell.row)
print("单元格的列号:",cell.column)
print("单元格的坐标:",cell.coordinate)
输出结果:
单元格的行号: 5
单元格的列号: A
单元格的坐标: A5
# 取某一单元格
cell = sheet['A1']
# 取一列单元格
cells = sheet['A']
# 取一行单元格
cells = sheet[1]
# 取表格当中的所有列,一列为一组
cells = sheet.columns
# 取表格当中的所有行,一行为一组
cells = sheet.rows
# 已知单元格列范围坐标时
cells = sheet['A:C']
cells = sheet['1:3']
# 已知单元格矩形范围坐标时
cells = sheet['A1:C5']
# 已知单元格起始与终结的行列数时
cells = sheet.iter_cols(min_row=1, max_row=5, min_col=1, max_col=3)
cells = sheet.iter_rows(min_row=1, max_row=5, min_col=1, max_col=3)
workbook.active 打开活跃的/唯一的表格
cell.value 格子的数据
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
cell = sheet['A1']
print(cell.value)
sheet.iter_rows(min_row=最低行数,max_row=最高行数,min_col=最低列数,max_col=最高列数): # 行
sheet.iter_cols(min_row=最低行数,max_row=最高行数,min_col=最低列数,max_col=最高列数): # 列
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
for row in sheet.iter_rows(min_row=2,max_row=3,min_col=1,max_col=2):
print(row)
# for row in sheet.iter_cols(min_row=2,max_row=3,min_col=1,max_col=2):
# print(row)
.rows
.columns
# 遍历所有的行
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
获取所有的行
for row in sheet.rows:
print(row)
# 遍历所有的列
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
for col in sheet.columns:
print(col)
输出结果:
(
, | , | , | … |
结果一样,输出顺序不一样。
.insert_cols(idx=数字编号,amount=要插入的列数)
.insert_rows(idx=数字编号,amount=要插入的行数)
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet.insert_cols(idx=2)
# sheet.insert_rows(idx=2) # 插入一行
workbook.save(filename='写入表格.xlsx')
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet.insert_cols(idx=2,amount=3)
# sheet.insert_rows(idx=2,amount=3) # 插入多行
workbook.save(filename='写入表格.xlsx')
.delete_cols(idx=数字编号,amount=要删除的列数)
.delete_rows(idx=数字编号,amount=要删除的行数)
在idx列这一行/列开始,包括idx这一行/列
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet.delete_cols(idx=2)
# sheet.delete_rows(idx=2) # 删除一行
workbook.save(filename='写入表格.xlsx')
append()方法接收一个可变参数,包括但不限于列表、范围或生成器或字典
如果传入一个列表:从第一列开始顺序添加所有值,列表元素对应每一行
如果传入一个字典:值被分配给键(数字或字母)指示的列
注意:append一次只能添加一行的数据,如果想要多行添加,需要与循环或其他方法相结合实现。
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
data = [
[‘张三',1],[‘李四',2],[‘王五',3],[‘赵六',4],
]
for row in data:
sheet.append(row)
workbook.save(filename='写入表格.xlsx')
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet['A1'] = 'test'
workbook.save(filename='写入表格.xlsx')
输出结果:
表格[A1]:test
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
cell = sheet['A1']
cell.value = 'test'
workbook.save(filename='写入表格.xlsx')
输出结果:
表格[A1]:test
sheet.cell(row=行数,column=列数)
cell.value = ‘内容’ # 为单元格赋值
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
cell = sheet.cell(row=1,column=1)
cell.value = 'test'
输出结果:
表格[A1]:test
直接赋值公式字符串
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet['B6'] = '=SUM(B2:B5)'
workbook.save(filename='写入表格.xlsx')
查看openpyxl支持的公式
from openpyxl.utils import formulas
print (formulas)
根据这个路径打开相应的formulas.py,显示如下:
FORMULAE = (“CUBEKPIMEMBER”, “CUBEMEMBER”, “CUBEMEMBERPROPERTY”, “CUBERANKEDMEMBER”, “CUBESET”,
…
.move_range(‘C1:D4’,rows=2,cols=-2)
正整数为向下或者向右,负整数为向左或者向上,类似于剪贴CTRL+X功能。
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
sheet = workbook.active
sheet.move_range("C1:D4", rows=2, cols=-2)
workbook.save(filename='写入表格.xlsx')
设置表格为隐藏状态:sheet.sheet_state = 'hidden'
设置表格为显示状态:sheet.sheet_state = 'visible'
from openpyxl import load_workbook
workbook = load_workbook(filename="写入表格.xlsx")
print(workbook.sheetnames)
m = input("是否要隐藏工作表Y/N:")
if m == "Y" or "y":
sheet = workbook.active
sheet.sheet_state = 'hidden'
else:
sheet = workbook.active
sheet.sheet_state = 'visible'
workbook.save(filename='写入表格.xlsx')
sheet.freeze_panes = “单元格”
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook.active
sheet.freeze_panes = "B2"
workbook.save(filename='4600本书单名.xlsx')
auto_filter.ref
from openpyxl import load_workbook
workbook = load_workbook(filename="4600本书单名.xlsx")
sheet = workbook['Booklist 12-26']
sheet.auto_filter.ref = sheet.dimensions # 对整张表进行筛选
workbook.save(filename='4600本书单名.xlsx')
cell.font.属性
from openpyxl.styles import Font
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell = sheet['A1']
font = cell.font
print('font.name是:',font.name,'font.size是:',font.size,'是否粗体:',font.bold,'是否斜体:',font.italic)
font = Font(name=‘字体名称’,size =字体大小,bold = 是否粗体,italic = 是否斜体,color =‘字体颜色’)
from openpyxl.styles import Font
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell = sheet['A1']
font = Font(name='宋体',size =12,bold = True,italic = True,color ='FF0000')
cell.font =font
workbook.save(filename='写入表格.xlsx')
可以通过设置单元格的风格来设置单元格格式分类
[openpyxl所支持的excel的单元格格式][https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html?highlight=openpyxl.styles.numbers]
from openpyxl.styles import Font
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell = sheet['A1']
# 设置单元格分类为百分比
cell.style = '百分比'
cell.style = '常规'
# 常规单元格
cell.number_format = 'General'
# 百分比单元格
cell.number_format = '0.00%'
# 科学计数法
cell.number_format = '0.00E+00'
workbook.save(filename='写入表格.xlsx')
Alignment(horizontal=水平对齐模式,vertical=垂直对齐模式,text_rotation=旋转角度,wrap_text=是否自动换行)
from openpyxl.styles import Alignment
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell = sheet['A1']
alignment = Alignment(horizontal='center',vertical='center',text_rotation=45)
cell.alignment =alignment
workbook.save(filename='写入表格.xlsx')
horizontal:'distributed', 'justify','center','left';'fill', 'centerContinuous','right",'general'
vertical:'bottom', 'distributed','justify','center';'top'
wrap_text:布尔类型,设置是否自动换行
textRotation:整数类型,设置文本旋转角度,最大值180
side = Side(style=边线样式,color=边线颜色)
border = Border(left=左边线样式,right=右边线样式,top=上边线样式,bottom=下边线样式)
from openpyxl.styles import Side, Border
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell = sheet['A1']
side = Side(style='thin',color='FF000000')
border = Border(left=side,right=side,top=side,bottom=side)
cell.border=border
workbook.save(filename='写入表格.xlsx')
side.style:
'double','mediumDashDotDot','slantDashDot','dashDotDot','dotted', 'hair', 'mediumDashed', 'dashed' 'dashDot' ,'thin', 'Dash Dot', 'medium', 'thick'
PatternFill(fill_type=填充样式,fgColor=填充颜色)
GradientFill(stop=(渐变颜色1,渐变颜色2,渐变颜色3…))
from openpyxl.styles import PatternFill, GradientFill
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
cell_a1 = sheet['A1']
pattern_fill = PatternFill(fill_type='solid',fgColor='00B0F0')
cell_a1.fill = pattern_fill
cell_b4 = sheet['B4']
gradient_fill = GradientFill(stop=('FFFFFF', '99CCFF', '000000'))
cell_b4.fill = gradient_fill
workbook.save(filename='写入表格.xlsx')
.row_dimensions[行编号].height = 行高
.column_dimensions[列编号].width = 列宽
from openpyxl.styles import PatternFill, GradientFill
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
sheet.row_dimensions[1].height = 50
sheet.column_dimensions['B'].width = 20
workbook.save(filename='写入表格.xlsx')
sheet.merge_cells(‘合并的范围’)
sheet.merge_cells(start_row=起始行号,start_column=起始列号,end_row=结束行号,end_column=结束列号)
from openpyxl.styles import PatternFill, GradientFill
from openpyxl import load_workbook
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
sheet.merge_cells('C1:C2')
sheet.merge_cells(start_row=7,start_column=1,end_row=8,end_column=4)
workbook.save(filename='写入表格.xlsx')
openpyxl.drawing.image
sheet.add_image
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
workbook = load_workbook(filename='写入表格.xlsx')
sheet = workbook.active
logo = Image("butterfly.png")
logo.height = 100
logo.width = 100
sheet.add_image(logo, "D1")
workbook.save(filename='写入表格.xlsx')
表数据【A1:C7】
项目 | 产值 | 数量 |
---|---|---|
A | 1802 | 18 |
B | 2098 | 20 |
C | 2668 | 26 |
D | 3537 | 35 |
E | 3650 | 36 |
F | 1068 | 15 |
BarChart() Reference()
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
workbook = load_workbook(filename='图表.xlsx')
sheet = workbook.active
chart = BarChart()
data = Reference(worksheet=sheet, min_row=1, max_row=7, min_col=2, max_col=3)
categories = Reference(sheet,min_col=1,min_row=2,max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
sheet.add_chart(chart, "E2")
workbook.save(filename='图表.xlsx')
表数据【A19:M21】
月份 | 广东 | 上海 | 北京 | 辽宁 | 天津 | 重庆 | 四川 | 浙江 | 江苏 | 安徽 | 江西 | 福建 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
一月 | 221 | 279 | 160 | 340 | 276 | 224 | 326 | 174 | 406 | 454 | 46 | 146 |
二月 | 364 | 136 | 423 | 77 | 467 | 33 | 454 | 46 | 462 | 129 | 371 | 108 |
LineChart()
from openpyxl import load_workbook
from openpyxl.chart import LineChart, Reference
workbook = load_workbook(filename='图表.xlsx')
sheet = workbook.active
chart = LineChart()
# data = Reference(worksheet=sheet, min_row=1, max_row=7, min_col=2, max_col=3)
# categories = Reference(sheet,min_col=1,min_row=2,max_row=7)
data = Reference(worksheet=sheet, min_row=20, max_row=21, min_col=1, max_col=13)
categories = Reference(sheet, min_col=2, min_row=19, max_col=13)
chart.add_data(data, from_rows=True, titles_from_data=True)
chart.set_categories(categories)
sheet.add_chart(chart, "E2")
workbook.save(filename='图表.xlsx')