使用的库
openpyxl
1 | import openpyxl |
作用的对象
文件后缀名为 .xlsx
excel几个操作单元
- 工作簿 workbook
- 表单 wooksheet
- 行、列、单元格 row, column, cell
常见操作
读取文件
1
2path = '../file/CIBES48配件统计.xlsx'
wb = openpyxl.load_workbook(path)
wb –> wookbook
获取表单
1
print(wb.sheetnames)
遍历表单
1
2for sheet in wb:
print(sheet.title)创建表单
1
mySheet = wb.create_sheet('mySheet')
得到具体某个表单
1
2sheet4 = wb.get_sheet_by_name('sheet4')
sheet3 = wb['mySheet']获得激活的表单
1
ws = wb.active
获得具体的某个单元格
1
2
3
4
5ws = wb.active
print('Row {}, Column {} is {}'.format(c.row, c.column, c.value))
print('Cell {} is {}\n'.format(c.coordinate, c.value))
print(ws.cell(row=4, column=1))
print(ws.cell(row=4, column=1).value) // .value 是取值遍历整行信息
1
2
3a = wb['Sheet1']
for i in range(1, 39, 1):
print(i, a.cell(row=1, column=i).value)获取整行或者整列信息
1
2
3
4
5
6
7colC = a['C']
print(colC[2].value)
row6 = a[6]
row_range = a[2:6]
for cow in row_range:
for cell in cow:
print(cell.value)高级一点的遍历
1
2
3for row in a.iter_rows(min_col=1, max_col=2, max_row=2):
for cell in row:
print(cell)打印列
1
print(tuple(a.rows))
每一列(或行)是一个生成器,这边用元组tuple来包起来;
这里面打印的是一个元组,元组里面每一个都是一个元组,要想获得具体的值,需要两次遍历;
1
2
3for i in tuple(a.rows):
for val in i:
print(val.value)切片
1
cell_range = a['A1:B3']
先行后列遍历切片
1
2
3
4for rowOfCwllObjects in cell_range:
for cellObj in rowOfCwllObjects:
print(cellObj.coordinate, cellObj.value)
print('------本行结束------')利用属性获得表格行列
1
print('{} * {}'.format(a.max_row, a.max_column))
处理列标 AA AB的问题 –>将列标改为数字
导包
1
from openpyxl.utils import get_column_letter, column_index_from_string
分别为 字母变数字 和 数字变字母 的包
1
print(get_column_letter(2), get_column_letter(47), get_column_letter(900))
打印第2列、第47列和第900列的字母是啥;
1
print(column_index_from_string('AAH'))
打印 AAH 列是多少列;