在 python 中打印 excel 单元格值时出错

Error while printing excel cell value in python

我是 python 的新手。最近我正在尝试在 windows 7 中使用 openpyxl 处理 excel 文件。我正在尝试打印 excel 文件 'Sample.xlsx' 中每个单元格的值。这是我的代码:

import openpyxl
workbook = openpyxl.load_workbook('Sample.xlsx')
worksheet = workbook.active
for row in worksheet.rows:
    for col in worksheet.columns:
        cell = worksheet.cell(row = row, column = col)
        print(cell.value)

当我 运行 脚本时出现以下错误:

Traceback (most recent call last): File "excel.py", line 6, in cell = worksheet.cell(row = row, column = col) File "C:\Python34\lib\site-packages\openpyxl\worksheet\worksheet.py", line 306, in cell if row < 1 or column < 1: TypeError: unorderable types: tuple() < int()

我无法理解错误。任何人都请解释我做错了什么。

尝试将 worksheet.rows 替换为 worksheet.iter_rows(min_row, max_row) 并将 worksheet.columns 替换为 worksheet.iter_cols(min_col, max_col),其中最小值和最大值是循环范围。我认为 worksheet.rows 给出了一个元组,你不能将它用于 for 循环。 iter_rows()iter_cols() returns 生成器所以它应该工作。

worksheet.cell 期望其 rowcolumn 参数基于 1 的索引,但是您传递了一个元组(worksheet.rowsworksheet.columns 每个 return一个元组的元组)。

你有几个选择:

  1. 利用 workbook.rows 按行迭代工作 sheet 并且 return 每行的单元格元组这一事实。这也为您节省了对 worksheet.cell:

    的调用
    for row in worksheet.rows:
        for cell in row:
            print(cell.value)
    

    相同,但按列排列:

    worksheet = workbook.active
    for column in worksheet.columns:
        for cell in column:
            print(cell.value)
    
  2. 使用max_rowmax_column获取此sheet中使用的最大行和列的索引(从1开始),然后用 range 迭代它们(同时记住 range 默认情况下是从零开始的和排他的:

    for row in range(1, worksheet.max_row + 1):
        for col in range(1, worksheet.max_column + 1):
            cell = worksheet.cell(row = row, column = col)
            print(cell.value)
    
  3. 使用 worksheet.get_cell_collection 获取包含所有已用单元格的可迭代对象,从而避免显式调用 worksheet.cell
    这种方法的问题是 returned 迭代的顺序是任意的:

    for cell in worksheet.get_cell_collection():
       print(cell.value)
    

我尝试了多种方法来打印 excel sheet 中单元格的值。这是我试过的代码:

    import openpyxl
    workbook = openpyxl.load_workbook('Sample.xlsx')
    worksheet = workbook.active
    for row in range(1,worksheet.max_row+1):
        for col in range(1,worksheet.max_column+1):
            print(worksheet.cell(row=row, column=col).value)

    import openpyxl
    workbook = openpyxl.load_workbook('Sample.xlsx')
    worksheet = workbook.active
    for row in worksheet.rows:
        for cell in row:
            print(cell.value)

    import openpyxl
    workbook = openpyxl.load_workbook('Sample.xlsx')
    worksheet = workbook.active
    for row in worksheet.iter_rows(worksheet.min_row, worksheet.max_row):
        for cell in row:
            print(cell.value)