VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python Excel处理库openpyxl详解(2)

上面的代码就可以获得所有单元格的数据。如果要获得某行的数据呢?给其一个索引就行了,因为sheet.rows是生成器类型,不能使用索引,转换成list之后再使用索引,list(sheet.rows)[2]这样就获取到第二行的tuple对象。

1
2
for cell in list(sheet.rows)[2]:
  print(cell.value)

 

如何获得任意区间的单元格?

可以使用range函数,下面的写法,获得了以A1为左上角,B3为右下角矩形区域的所有单元格。注意range从1开始的,因为在openpyxl中为了和Excel中的表达方式一致,并不和编程语言的习惯以0表示第一个值。

1
2
3
4
5
6
7
8
9
10
11
for in range(14):
  for in range(13):
    print(sheet.cell(row=i, column=j))
    
# out
<Cell pythontab.A1>
<Cell pythontab.B1>
<Cell pythontab.A2>
<Cell pythontab.B2>
<Cell pythontab.A3>
<Cell pythontab.B3>

 

还可以像使用切片那样使用。sheet['A1':'B3']返回一个tuple,该元组内部还是元组,由每行的单元格构成一个元组。

1
2
3
4
5
6
7
8
9
10
for row_cell in sheet['A1':'B3']:
  for cell in row_cell:
    print(cell)
    
for cell in sheet['A1':'B3']:
  print(cell)
# out
(<Cell pythontab.A1>, <Cell pythontab.B1>)
(<Cell pythontab.A2>, <Cell pythontab.B2>)
(<Cell pythontab.A3>, <Cell pythontab.B3>)

 

根据字母获得列号,根据列号返回字母

 

需要导入, 这两个函数存在于openpyxl.utils

1
2
3
4
5
from openpyxl.utils import get_column_letter, column_index_from_string
# 根据列的数字返回字母
print(get_column_letter(2)) # B
# 根据字母返回列的数字
print(column_index_from_string('D')) # 4

相关教程