Dan*_*hms 17 excel python-2.7 openpyxl
我无法弄清楚如何使用openpyxl遍历指定列中的所有行.
我想打印"C"列中所有行的所有单元格值
现在我有:
from openpyxl import workbook
path = 'C:/workbook.xlsx'
wb = load_workbook(filename = path)
ws=wb.get_sheet_by_name('Sheet3')
for row in ws.iter_rows():
for cell in row:
if column == 'C':
print cell.value
Run Code Online (Sandbox Code Playgroud)
小智 23
为什么不能迭代列'C'(版本2.4.7):
for cell in ws['C']:
print cell.value
Run Code Online (Sandbox Code Playgroud)
ber*_*nie 22
您可以指定要迭代的范围ws.iter_rows():
import openpyxl
wb = openpyxl.load_workbook('C:/workbook.xlsx')
ws = wb.get_sheet_by_name('Sheet3')
for row in ws.iter_rows('C{}:C{}'.format(ws.min_row,ws.max_row)):
for cell in row:
print cell.value
Run Code Online (Sandbox Code Playgroud)
编辑:根据查理克拉克你可以交替使用ws.get_squared_range():
# ...
ws.get_squared_range(min_col=1, min_row=1, max_col=1, max_row=10)
# ...
Run Code Online (Sandbox Code Playgroud)
编辑2:根据您的评论,您需要列表中的单元格值:
import openpyxl
wb = openpyxl.load_workbook('c:/_twd/2016-06-23_xlrd_xlwt/input.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
mylist = []
for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
for cell in row:
mylist.append(cell.value)
print mylist
Run Code Online (Sandbox Code Playgroud)
小智 7
你也可以这样做。
for row in ws.iter_rows():
print(row[2].value)
Run Code Online (Sandbox Code Playgroud)
有了这个,您仍然在遍历行(但不是单元格),并且只从行中的列 C 中提取值进行打印。
上面的一些解决方案不太有效(可能是因为最新版本的“openpyxl”)。在尝试了不同的东西之后,我使用了这个:
import openpyxl
sheet = openpyxl.load_workbook('myworkbook.xlsx')['Sheet1']
# Iterating through All rows with all columns...
for i in range(1, sheet.max_row+1):
row = [cell.value for cell in sheet[i]] # sheet[n] gives nth row (list of cells)
print(row) # list of cell values of this row
Run Code Online (Sandbox Code Playgroud)
# For example we need column 'E' to column 'L'
start_col = 4 # 'E' column index
end_col = 11 # 'L' column index
for i in range(1, sheet.max_row+1):
row = [cell.value for cell in sheet[i][start_col:end_col+1]]
print(row) # list of cell values of this row
Run Code Online (Sandbox Code Playgroud)
请记住以下几点:
| 归档时间: |
|
| 查看次数: |
42714 次 |
| 最近记录: |