||每日一句||
“事事如意料之外,年年有余额不足”
全文773字 预计阅读6分钟
在讲解之前,首先介绍一下,在python语言中,Excel相关元素的字母表示。
下面的练习都是对如下的表格进行处理,练习文件已上传至蓝奏云,请至此链接进行下载:https://zhgv.lanzous.com/iCtakj3t5xe
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")print(MyExcel.sheetnames)
打印如下:
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")# 通过sheet名称获取表格sheet = MyExcel["表1"]print(sheet.dimensions)
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")sheet = MyExcel["表1"]# sheet["A4"] 获取A1格子的数据;cell1 = sheet["A4"]# cell.value 获取格子中的值;print(cell1.value);
这是一种更为简单直观的方式。
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")sheet = MyExcel["表1"]# sheet["A4"] 获取A1格子的数据;cell1 = sheet.cell(row = 2,column = 1)cell2 = sheet.cell(row = 6,column = 3)print(cell1.value, cell2.value)
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")sheet = MyExcel["表1"]# sheet.cell(row=num1,column=num2)获取第二行,第一列的数据;cell1 = sheet.cell(row = 2,column = 1)# .row 获取某个格子的行数;# .columns 获取某个格子的列数;# .coordinate 获取某个格子的坐标;print(cell1.value, cell1.row, cell1.column, cell1.coordinate)
读取行列的方式有两种,这边仅介绍其中一种.iter_rows()方式,掌握一种即可。注意,我这里为了方便截图展示添加了end='\t'不换行。
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")sheet = MyExcel["表1"]# 按行获取值for i in sheet.iter_rows(min_row=2, max_row=5, min_col=1, max_col=2): for j in i: print(j.value,end='\t')
from openpyxl import load_workbookMyExcel = load_workbook(filename="1.xlsx")sheet = MyExcel["表1"]# 按列获取值for i in sheet.iter_cols(min_row=2, max_row=5, min_col=1, max_col=2): for j in i: print(j.value,end='\t')
-END-
▼
推荐阅读