pip3 install openpyxl
pip3 install pillow
from openpyxl import Workbook
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active
ws1.title = "range names"
ws1['F5'] = 3.14
print(ws1['F5'].value)
wb.save(filename = dest_filename)
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
print(wb.sheetnames)
| 选项 | 说明 |
|---|---|
| read_only=True | 只读模式,节省内存,必须使用close()关闭 |
| write_only = True | 只写模式, |
| 属性 | 说明 |
|---|---|
| active | 获取当前活跃的Worksheet |
| worksheets | 以列表的形式返回所有的Worksheet(表格) |
| data_only | 默认为False,为True时只读取数据不显示公式 |
| read_only | 判断是否以read_only模式打开Excel文档 |
| encoding | 获取文档的字符集编码 |
| properties | 获取文档的元数据,如标题,创建者,创建日期等 |
| sheetnames | 获取工作簿中的表(列表) |
| 方法 | 说明 |
|---|---|
| 工作簿.sheetnames | 获取所有表格的名称 |
| 工作簿[‘工作表名’] | 通过表格名称获取Worksheet对象 |
| 工作簿.active | 获取活跃的表格 |
| remove | 删除一个工作表对象【对象】 |
| create_sheet | 创建一个空的表格【表名】 |
| copy_worksheet | 在Workbook内拷贝表格【对象】 |
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
for sheet in wb:
print(sheet.title)
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.Workbook()
ws1 = wb.create_sheet("Mysheet_1") # 在末尾插入工作表(默认值)
ws2 = wb.create_sheet("Mysheet_2", 0) # 在最前插入工作表
ws3 = wb.create_sheet("Mysheet_3", -1) #在倒数第二位插入
ws3.sheet_properties.tabColor = "1072BA" # 设置工作表背景
wb.save(filename = file1)
ws = wb.worksheets[0]
ws = wb['4月']
import openpyxl
file1 = '文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb['4月']
wb.remove(ws)
wb.save(file1)
import openpyxl
file1 = '文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.copy_worksheet(wb['Sheet']) # 这里是工作表对象
ws.title = "新复制工作表"
wb.save(file1)
rows = ws.max_row
columns = ws.max_column
import openpyxl
file1 = 'd:\\06fping_net.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
tab = openpyxl.worksheet.table.Table(displayName="Table1", ref=ws.dimensions)
# Add a default style with striped rows and banded columns
style = openpyxl.worksheet.table.TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=False)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save(file1)
del ws.tables["Table1"]
| 属性 | 说明 |
|---|---|
| title | 工作表的名称 |
| dimensions | 表格的大小,这里的大小是指含有数据的表格的大小,即:左上角的坐标:右下角的坐标 |
| max_row | 表格的最大行 |
| min_row | 表格的最小行 |
| max_column | 表格的最大列 |
| min_column | 表格的最小列 |
| rows | 按行获取单元格(Cell对象) - 生成器 工作表.rows |
| columns | 按列获取单元格(Cell对象) - 生成器 工作表.columns |
| freeze_panes | 冻结窗格 工作表.freeze_panes = “C3” |
| sheet_properties.tabColor | 工作表背景色如:“1072BA” |
| values | 按行获取表格的内容(数据) - 生成器 |
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
for row in ws.values:
for value in row:
print(value)
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
# values_only=True 参数,可以仅仅获取value
for row in ws.iter_rows(min_row=1, max_col=3, max_row=3,values_only=True):
for cell in row:
# 按行遍历单元格
print(cell.value)
A1
B1
C1
A2
B2
C2
A3
B3
C3
import openpyxl
file1 = r'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
for col in ws.iter_cols(min_row=1, max_col=3, max_row=3):
for cell in col:
# 按列遍历单元格
print(cell.value)
A1
A2
A3
B1
B2
B3
C1
C2
C3
| 方法 | 说明 |
|---|---|
| iter_rows | 按行获取所有单元格,内置属性有(min_row,max_row,min_col,max_col) |
| iter_columns | 按列获取所有的单元格 |
| append | 在表格末尾添加数据 |
| merged_cells | 合并多个单元格 |
| unmerged_cells | 移除合并的单元格 |
con = ["序号","编号","速率(G)","接口","状态","分配","模块","接口描述"]
#ws为工作表对象
ws.append(con)
con = ["序号","编号","速率(G)","接口","状态","分配","模块","接口描述"]
#ws为工作表对象
ws.append(con)
| 表示 | 说明 |
|---|---|
| ws[‘A1:C10’] | A1:C10区域 |
| ws[‘1:10’] | 1到10行 |
| ws[‘A:C’] | A到C列 |
| 方法 | 说明 |
|---|---|
| row | 单元格所在的行 |
| column | 单元格坐在的列 |
| value | 单元格的值 |
| coordinate | 单元格的坐标 |
import openpyxl
file1 = 'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
print(ws["B10"].value)
print(ws.cell(row=1,column=3).value)
print(ws.cell(1,3).value)
import openpyxl
file1 = 'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
rng = ws["A1:C10"]
for row in rng: # 循环每行
for cell in row: # 循环每个单元格
print(cell.value)
ws.move_range("D4:F10", rows=-1, cols=2)
import openpyxl
file1 = Path('d:\\文件名称.xlsx')
wb = openpyxl.Workbook()
ws1 = wb.active
wb.create_sheet('temp1')
# 设置网址超链接
url = "http://www.baidu.com"
ws1.cell(row = 1,column = 1).value = '=HYPERLINK("{}","{}")'.format(url,'百度')
# 设置文件内超链接
link = f"{ file1.name }#temp1!A1"
ws1.cell(row = 2,column = 2).value = '=HYPERLINK("{}","{}")'.format(link,'temp表')
# 设置单元格为蓝色
ws1.cell(row = 1,column = 1).style = "Hyperlink"
ws1.cell(row = 2,column = 2).style = "Hyperlink"
wb.save(filename = file1)
import openpyxl
file1 = 'd:\\文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
ws = wb.active
ws["A5"].number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[10]
ws["A5"].value = 0.02
wb.save(file1)
from openpyxl.workbook import Workbook
wb = Workbook()
ws = wb.active
ws.merge_cells('A2:D2')
ws.unmerge_cells('A2:D2')
# or equivalently
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)
工作表.row_dimensions[1].height = 200
工作表.column_dimensions['B'].width = 100
from openpyxl.utils import get_column_letter
col = 5
sht.column_dimensions[get_column_letter(col)].width = 18
import datetime
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# set date using a Python datetime
ws['A1'] = datetime.datetime(2010, 7, 21)
ws['A1'].number_format
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# add a simple formula
ws["A1"] = "=SUM(1, 1)"
wb.save("formula.xlsx")
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule,Rule
wb = Workbook()
ws = wb.active
# 创建填充'redFill'
redFill = PatternFill(start_color='EE1111',
end_color='EE1111',
fill_type='solid')
# 添加双色刻度'A1:A10'
# 采用excel“RRGGBB”风格的颜色。
ws.conditional_formatting.add('A1:A10',
ColorScaleRule(start_type='min', start_color='AA0000',
end_type='max', end_color='00AA00')
)
# 添加一个三色刻度'B1:B10'
ws.conditional_formatting.add('B1:B10',
ColorScaleRule(start_type='percentile', start_value=10, start_color='AA0000',
mid_type='percentile', mid_value=50, mid_color='0000AA',
end_type='percentile', end_value=90, end_color='00AA00')
)
# 基于单元格比较添加条件格式'C2:C10'
# addCellIs(范围字符串、运算符、公式、stopIfTrue、wb、字体、边框、填充)
# 如果单元格小于“公式”,则设置格式
ws.conditional_formatting.add('C2:C10',
CellIsRule(operator='lessThan', formula=['C$1'], stopIfTrue=True, fill=redFill))
# 如果单元格位于“公式”之间,则设置格式
ws.conditional_formatting.add('D2:D10',
CellIsRule(operator='between', formula=['1','5'], stopIfTrue=True, fill=redFill))
# 使用公式格式化
ws.conditional_formatting.add('E1:E10',
FormulaRule(formula=['ISBLANK(E1)'], stopIfTrue=True, fill=redFill))
# 除了2色和3色刻度之外,格式规则采用字体、边框和填充进行样式设置:
myFont = Font()
myBorder = Border()
ws.conditional_formatting.add('E1:E10',
FormulaRule(formula=['E1=0'], font=myFont, border=myBorder, fill=redFill))
# 使用特殊公式高亮显示包含特定文本的单元格
red_text = Font(color="9C0006")
red_fill = PatternFill(bgColor="FFC7CE")
dxf = DifferentialStyle(font=red_text, fill=red_fill)
rule = Rule(type="containsText", operator="containsText", text="highlight", dxf=dxf)
rule.formula = ['NOT(ISERROR(SEARCH("highlight",A1)))']
ws.conditional_formatting.add('A1:F40', rule)
wb.save(r"d:\\test.xlsx")
import openpyxl
file1 = '文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
for i in range(1,12):
wb.create_sheet(f'{ i }月')
wb.save(file1)
import openpyxl
file1 = '文件名称.xlsx'
wb = openpyxl.load_workbook(file1)
AllWS = wb.sheetnames
for ws in AllWS:
if ws != "9月":
wb.remove(wb[ws])
wb.save(file1)