ws1 = wb1["student"]for i_row in ws1["A1:C3"]:for i_cell in i_row:print(i_cell.value)for i_row in ws1["A1:C3"]:print([i_cell.value for i_cell in i_row])
1
2
3
4
5
6
7
ws1 = wb1["student"]for i_col in ws1["A:C"]:for i_cell in i_col:print(i_cell.value)for i_col in ws1["A:C"]:print([i_cell.value for i_cell in i_col])
from openpyxl import*file=r"D:\xlsx\lianxi_3.xlsx"
wb1 = load_workbook(file)# 遍历
list1 =[]for i_ws in wb1.worksheets:
list1.append(i_ws["A2"].value)print(sum(list1))#列表推导式print(sum(i_ws["A2"].value for i_ws in wb1.worksheets))
1
2
3
4
5
6
7
8
9
10
11
12
24
24
1
2
按行或列求和
from openpyxl import*file=r"D:\xlsx\lianxi_4.xlsx"
wb1 = load_workbook(file)
ws1 = wb1.worksheets[0]# for i_col in ws1.columns:# print(i_col)
rg1 =list(ws1.columns)[1:]print(rg1,len(rg1))
list1 =[]for i_col in rg1:for i_cell in i_col:
list1.append(i_cell.value)print(sum(list1[1:]))print([i_cell.value for i_cell in i_col for i_col inlist(ws1.columns)[1:]])print(sum(([i_cell.value for i_cell in i_col for i_col inlist(ws1.columns)[1:]])[1:]))