1,概念
openpyxl定义多种数据格式
- 最重要的三种:
NULL空值:对应于python中的None,表示这个cell里面没有数据。
numberic: 数字型,统一按照浮点数来进行处理。对应于python中的float。
string: 字符串型,对应于python中的unicode。
Excel文件三个对象
workbook: 工作簿,一个excel文件包含多个sheet。
sheet:工作表,一个workbook有多个,表名识别,如“sheet1”,“sheet2”等。
cell: 单元格,存储数据对象
2,安装
pip install openpyxl
3,打开文件
-
创建文件
from openpyxl import Workbook
# 实例化
wb = Workbook()
-
打开已有文件
from openpyxl import load_workbook
wb = load_workbook('文件名称.xlsx')
4,创建表
# 方式一: 激活 worksheet
sheet1 = wb.active
# 方式二:插入到最后(default)
sheet2 = wb.create_sheet(title="Mysheet")
# 方式三: 指定 表的名称和索引(也就是第几个sheet)
sheet3 = wb.create_sheet(title="hello", index=0)
5, 选择表(sheet)
方式一:直接通过表名来选取
ws = wb["New Title"]
ws2 = wb.get_sheet_by_name("New Title")
方式二:通过获取工作簿中所有表名 根据表名再获取表对象
ws = workbook.get_sheet_names() # 已经要弃用的
# index为0为第一张表
ws = workbook.get_sheet_by_name(sheet_names[0]) # 已经要弃用的
方式三:获取正在操作的表对象
#通过_active_sheet_index设定读取的表,默认0读第一个表
ws3 = workbook.active
ws4 = workbook.get_active_sheet()
6,获取所有表名
方式一
sheetnames=wb.sheetnames
# ['Sheet2', 'New Title', 'Sheet1']
方式二
sheet_names = wb.get_sheet_names()
方式三
for sheet in wb:
print(sheet.title)
7,修改表名称
ws.title = "New Title"
8,读取单元格
方式一
通过坐标获取
# 先获取到cell对象 用通过value属性获取到值
cell=sheet['A1']
print(cell) # <Cell 'Sheet1'.A1>
print(cell.value) # text
方式二
通过坐标获取
cell = ws.cell(row=4, column=2)
方式三
遍历获取
for i in range(1,101):
for j in range(1,101):
ws.cell(row=i, column=j)
9,写入单元格
方式一
ws['A4'] = 4
方式二
# value参数默认值为None,如果为None,只是获取这个cell对象,如果有,那么会修改这个cell的值为value的值
cell=ws.cell(row=1, column=1,value=3000)
方式三
ws.cell(row = 4, column = 2).value = 'test'
方式四
append中的参数应为列表或元组。
sheet.append([1000, 2000, 3000])
10,多单元格访问
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
for cell in row:
print(cell)
方式二
colC = sheet['C']
for i in colC:
print(i.value)
print('-'*100)
col_range = sheet['C:D']
for col in col_range:
for i in col:
print(i.value)
print('-'*100)
row10 = sheet[4]
for i in row10:
print(i.value)
print('-'*100)
row_range = sheet[3:4]
for row in row_range:
for i in row:
print(i.value)
11,获取表的行数和列数
print(sheet.max_row)
print(sheet.max_column)
12,保存文件
wb.save('文件名称.xlsx')