以下是本篇文章正文内容
from openpyxl import Workbook,load_workbook
from openpyxl.styles import *
import warnings
warnings.filterwarnings('ignore')
wb1 = Workbook()
wb = load_workbook('./000.xlsx')
# openpyxl只能处理 .xlsx 合适的表格
ws1 = wb.create_sheet('111')
ws2 = wb.active
ws2.title
‘000’
ws = wb['000']
wb.sheetnames
[‘000’, ‘111’]
ws['A1']
ws.cell(1,1) # 先行后列,都是索引下标
cell = ws['A1']
1 .单元格列索引
cell.col_idx
1
cell.column
1
cell.row
1
cell.column_letter
‘A’
cell.coordinate
‘A1’
默认是n 数值
s 字符串
d 日期时间
cell.data_type
‘n’
cell.encoding
‘utf-8’
cell.has_style # 默认样式是 Normal,如果是默认样式,返回False
False
cell.style
‘Normal’
cell.style_id
0
属性样式会在后面设置中详细演示,此处只做查询
cell.font
Parameters:
name=‘Calibri’, charset=None, family=2.0, b=False, i=False, strike=None, outline=None, shadow=None, condense=None, color=
Parameters:
rgb=None, indexed=None, auto=None, theme=1, tint=0.0, type=‘theme’, extend=None, sz=11.0, u=None, vertAlign=None, scheme=‘minor’
cell.alignment
Parameters:
horizontal=None, vertical=None, textRotation=0, wrapText=None, shrinkToFit=None, indent=0.0, relativeIndent=0.0, justifyLastLine=None, readingOrder=0.0
cell.border
Parameters:
outline=True, diagonalUp=False, diagonalDown=False, start=None, end=None, left=
Parameters:
style=None, color=None, right=
Parameters:
style=None, color=None, top=
Parameters:
style=None, color=None, bottom=
Parameters:
style=None, color=None, diagonal=
Parameters:
style=None, color=None, vertical=None, horizontal=None
cell.fill
Parameters:
patternType=None, fgColor=
Parameters:
rgb=‘00000000’, indexed=None, auto=None, theme=None, tint=0.0, type=‘rgb’, bgColor=
Parameters:
rgb=‘00000000’, indexed=None, auto=None, theme=None, tint=0.0, type=‘rgb’
cell.number_format
‘General’
cell.hyperlink
ws['A1'].value
一列 字符串
ws['A']
(
一行,数字
ws[1]
(
ws['A:B']
((
(
多行
ws[5:10]
((
(
(
(
(
(
ws['A3:B9']
((
(
(
(
(
(
(
ws['A1'] = 20
ws.cell(2,2).value
‘陈桂荣’
当使用cell() 时,只能给value属性赋值
# ws.cell(2,2) = 20
# 会报错
ws.cell(2,2).value = 30
增加一行
ws.append([1,2,3])
ws.values 返回的是生成器,是将一行数据作为一个元组单元组成的,是由值组成的
ws.values 获取的内容是从 “A1” 到 “最大行最大列”
ws.values
for i in ws.values:
print(i)
(20, ‘NAME’, ‘DATE_TIME’, ‘PAY’)
(0, 30, datetime.datetime(1972, 2, 23, 3, 10, 2), 8803)
(1, ‘黄瑞’, datetime.datetime(1977, 11, 29, 4, 49, 16), 5951)
(2, ‘李阳’, datetime.datetime(1982, 8, 30, 18, 12, 46), 7418)
(3, ‘石淑英’, datetime.datetime(2016, 4, 18, 11, 24, 17), 737)
(4, ‘陈红霞’, datetime.datetime(2011, 12, 12, 3, 12, 47, 1), 3555)
(5, ‘廖健’, datetime.datetime(1989, 9, 25, 20, 9, 45, 1), 2649)
(6, ‘韩雪梅’, datetime.datetime(2002, 1, 2, 8, 0, 51), 7344)
(7, ‘赵丽丽’, datetime.datetime(2018, 7, 1, 19, 35, 24), 8735)
(8, ‘侯建华’, datetime.datetime(1971, 8, 1, 16, 59, 1), 6148)
(9, ‘谭桂花’, datetime.datetime(2000, 4, 7, 5, 2, 38), 8900)
(1, 2, 3, None)
for i in ws.iter_rows(min_col=1,max_col=3,min_row=1,max_row=10):
print(i)
(
(
(
(
(
(
(
(
(
(
ws.iter_rows()
ws.rows
是将一行单元格作为元组单元组成的生成器,与ws.values的区别是,rows返回的是由单元格组成的元组,values是由值组成的
import random
for i in ws.rows:
for j in i:
print(j,j.value)
columns 、iter_col() 是按列
ws.columns
for i in ws.columns:
print(i)
(
(
(
(
ws.iter_cols(min_col=1,max_col=3,min_row=1,max_row=10)
ws.max_column
4
ws.max_row
12
注意,删除行或者列后,后面的行或者列会自动往前填充,也就是说,删除第一列,原来的第二列就会变成第一列
ws.cell(1,2).value
‘NAME’
ws.delete_cols(1)
ws.cell(1,1).value
‘NAME’
ws.delete_rows(3)
for i in ws.rows:
for j in i:
print(j,j.value)
import pandas as pd
df = pd.DataFrame(ws.values)
df
for i in df.values:
ws.append(i.tolist())
for i in ws.rows:
for j in i:
print(j,j.value,end=',')
print('')
ws.merge_cells("A1:B1")
ws.merge_cells(start_column=3,end_column=6,start_row=2,end_row=3)
已存在的合并单元格
ws.merged_cells
已存在的合并单元格列表
ws.merged_cell_ranges
[< CellRange A1:B1>, < CellRange C2:F3>]
ws['A1'].value
‘NAME’
ws['B1'].value
合并后的单元格,只会保留最上角的值,其他单元格的值全部为空(None)
实际上,openpyxl可以添加过滤和排序,但是并不会起作用
# 过滤区域
ws.auto_filter.ref = "A:B"
# 给指定列添加过滤条件
ws.auto_filter.add_filter_column(0, ['ASC','DWS'])
ws.auto_filter.add_sort_condition("B2:B15")
Color(index=0) # 根据索引进行填充
#
Color(rgb='00000000') # 根据rgb值进行填充
# index
COLOR_INDEX = (
'00000000', '00FFFFFF', '00FF0000', '0000FF00', '000000FF', #0-4
'00FFFF00', '00FF00FF', '0000FFFF', '00000000', '00FFFFFF', #5-9
'00FF0000', '0000FF00', '000000FF', '00FFFF00', '00FF00FF', #10-14
'0000FFFF', '00800000', '00008000', '00000080', '00808000', #15-19
'00800080', '00008080', '00C0C0C0', '00808080', '009999FF', #20-24
'00993366', '00FFFFCC', '00CCFFFF', '00660066', '00FF8080', #25-29
'000066CC', '00CCCCFF', '00000080', '00FF00FF', '00FFFF00', #30-34
'0000FFFF', '00800080', '00800000', '00008080', '000000FF', #35-39
'0000CCFF', '00CCFFFF', '00CCFFCC', '00FFFF99', '0099CCFF', #40-44
'00FF99CC', '00CC99FF', '00FFCC99', '003366FF', '0033CCCC', #45-49
'0099CC00', '00FFCC00', '00FF9900', '00FF6600', '00666699', #50-54
'00969696', '00003366', '00339966', '00003300', '00333300', #55-59
'00993300', '00993366', '00333399', '00333333', #60-63
)
BLACK = COLOR_INDEX[0]
WHITE = COLOR_INDEX[1]
RED = COLOR_INDEX[2]
DARKRED = COLOR_INDEX[8]
BLUE = COLOR_INDEX[4]
DARKBLUE = COLOR_INDEX[12]
GREEN = COLOR_INDEX[3]
DARKGREEN = COLOR_INDEX[9]
YELLOW = COLOR_INDEX[5]
DARKYELLOW = COLOR_INDEX[19]
ws.cell(5,3).value='哈哈哈'
ws.cell(5,3).font = Font(name='仿宋',size=12,color=Color(index=0),b=True,i=True)
# size sz 字体大小
# b bold 是否粗体
# i italic 是否斜体
# name family 字体样式
Side(style='thin',color=Color(index=0))
# style可选项
style = ('dashDot','dashDotDot', 'dashed','dotted',
'double','hair', 'medium', 'mediumDashDot', 'mediumDashDotDot',
'mediumDashed', 'slantDashDot', 'thick', 'thin')
# 'medium' 中粗
# 'thin' 细
# 'thick' 粗
# 'dashed' 虚线
# 'dotted' 点线
Border(left=Side(),
right=Side(),
top=Side(),
bottom=Side())
Parameters:
outline=True, diagonalUp=False, diagonalDown=False, start=None, end=None, left=
Parameters:
style=None, color=None, right=
Parameters:
style=None, color=None, top=
Parameters:
style=None, color=None, bottom=
Parameters:
style=None, color=None, diagonal=
Parameters:
style=None, color=None, vertical=None, horizontal=None
ws.cell(3,3).border = Border()
PatternFill(patternType='solid',fgColor=Color(), bgColor=Color())
# fgColor 前景色
# bgColor 后景色
# 参数可选项
patternType = {
'darkDown', 'darkUp', 'lightDown', 'darkGrid', 'lightVertical',
'solid', 'gray0625', 'darkHorizontal', 'lightGrid', 'lightTrellis',
'mediumGray', 'gray125', 'darkGray', 'lightGray', 'lightUp',
'lightHorizontal', 'darkTrellis', 'darkVertical'}
ws.cell(3,3).fill = PatternFill()
Alignment(horizontal='fill',vertical='center')
# 参数可选项
horizontal = {
'fill', 'distributed', 'centerContinuous', 'right',
'justify', 'center', 'left', 'general'}
vertical = {
'distributed', 'justify', 'center', 'bottom', 'top'}
ws.cell(3,3).alignment= Alignment()
设置工作薄自动识别单元格样式
wb.guess_types = True
当设置为自动识别后,单元格赋值python类型即可,会自动识别为Excel的数字类型
ws['A11'] = '2020-09-22'
ws['A11'].value
‘2020-09-22’
ws['A11'].data_type
‘s’
ws['A11'].number_format
'General'
import datetime
ws['B11'] = datetime.datetime.now()
ws['B11'].value
datetime.datetime(2020, 11, 8, 9, 25, 37, 657654)
ws['B11'].number_format
'yyyy-mm-dd h:mm:ss'
ws['B11'].data_type
'd'
也可以使用内建样式
ws['B5'] = 50000
ws['B5'].number_format = '#,##0'
ws['B5'].data_type
'n'
也可以自定义样式
ws['B6'].number_format = 'yyyy-mm-dd'
ws['B6'] = datetime.datetime.now()
ws['B6'].value
datetime.datetime(2020, 11, 8, 9, 25, 37, 722481)
ws['B6'].data_type
'd'
内建数字样式
BUILTIN_FORMATS = {
0: 'General', # 默认样式
1: '0',
2: '0.00',
3: '#,##0',
4: '#,##0.00',
5: '"$"#,##0_);("$"#,##0)',
6: '"$"#,##0_);[Red]("$"#,##0)',
7: '"$"#,##0.00_);("$"#,##0.00)',
8: '"$"#,##0.00_);[Red]("$"#,##0.00)',
9: '0%',
10: '0.00%',
11: '0.00E+00',
12: '# ?/?',
13: '# ??/??',
14: 'mm-dd-yy',
15: 'd-mmm-yy',
16: 'd-mmm',
17: 'mmm-yy',
18: 'h:mm AM/PM',
19: 'h:mm:ss AM/PM',
20: 'h:mm',
21: 'h:mm:ss',
22: 'm/d/yy h:mm',
37: '#,##0_);(#,##0)',
38: '#,##0_);[Red](#,##0)',
39: '#,##0.00_);(#,##0.00)',
40: '#,##0.00_);[Red](#,##0.00)',
41: r'_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
42: r'_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
43: r'_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
44: r'_("$"* #,##0.00_)_("$"* \(#,##0.00\)_("$"* "-"??_)_(@_)',
45: 'mm:ss',
46: '[h]:mm:ss',
47: 'mmss.0',
48: '##0.0E+0',
49: '@', }
ws['C5'].value = '=HYPERLINK("#Sheet!B2","名称")'
from openpyxl.worksheet.hyperlink import Hyperlink
ws['C6'].hyperlink = Hyperlink(ref='',location='Sheet!H5',target='')
ws['C6'].value = '这是链接'
target : 目标文件
location :目标单元格 工作表名 + ! + 单元格名
如果需要显示蓝色字体和下划线,需要设置字体
link = NamedStyle(name='link',font=Font(color=colors.BLUE,underline='single'))
ws['C6'].style = link
bbb = NamedStyle(name='bbb',
font=Font(color=colors.BLUE),
fill=PatternFill(fgColor=Color(index=0)),
border=Border(left=Side(style='medium',color=Color(theme=6,tint=0.6)),
right=Side(style='medium',color='FFBB00'),
top=Side(),
bottom=Side()),
alignment=Alignment(horizontal='center',vertical='top')
)
可以将样式添加到工作薄,可以直接用字符串的形式赋值样式
wb.add_named_style(bbb)
ws['A5'].style=bbb
ws['A5'].value='自定义样式'
ws['A10'].style = 'bbb'
ws['A10'].style_id
3
ws['A10'].has_style
True
row =ws.row_dimensions[1]
row.height = 15
col = ws.column_dimensions['E']
col.width = 10
wb.save('./000.xlsx')