python循环读取excel列_Python-Excel-openpyxl-10-按行或者按列遍历

系统:Windows 7

语言版本:Anaconda3-4.3.0.1-Windows-x86_64

编辑器:pycharm-community-2016.3.2

openpyxl:2.6.2这个系列讲讲Python对Excel的操作

使用openpyxl模块

今天讲讲对某行某列进行遍历

Part 1:示例对Excel的行或列进行遍历

Excel中信息

Part 2:代码import os

from openpyxl import load_workbook

root_address = os.path.dirname(os.path.abspath(__file__))

excel_name = r"openpyxl示例_10.xlsx"

excel_address = os.path.join(root_address, excel_name)

print(excel_address)

wb = load_workbook(excel_address)

sht = wb.worksheets[0]

col = sht["A"]

i = 0

for cell in col:

i += 1

print("i=", i)

print("单元格内值", cell.value)

print("\n相隔3行\n")

row1 = sht[1]

row2 = sht[2]

j = 0

for cell in row1:

j += 1

print("j=", j)

print("单元格内值", cell.value)

print("\n相隔3行\n")

k = 0

for cell in row2:

k += 1

print("k=", k)

print("单元格内值", cell.value)

代码截图

运行结果

Part 3:部分代码解读for cell in col:对单元格区域进行遍历,cell.value为单元格内的值

获取工作表某一行:row1 = sht[行号],行号取值1,2,3,4

获取工作表某一列:col1 = sht[列号],列号取值A,B,C,D

从输出可以看出,实际上并没有遍历整个行或者列,而是在最大行及最大列间进行遍历

最大行最大列如何定义或者获取请参看之前的文章

你可能感兴趣的:(python循环读取excel列_Python-Excel-openpyxl-10-按行或者按列遍历)