如何在openpyxl和xlrd中获得单元格值?

时间:2018-07-02 13:12:32

标签: python openpyxl xlrd

我有以下工作代码,用于在excel文件中搜索关键字并打印其位置:

import openpyxl as xl 
import os 
import xlrd

file_extensions = ('.xlsx', '.xlsm', '.xls') 
keyword = 'EUROBUS' 
directory = 'M:\\moje makra'

def filenames(directory): 
    for root, dirs, filenames in os.walk(directory): 
        for filename in filenames: 
            if filename.endswith(file_extensions): 
                yield os.path.join(root, filename) 

for filename in filenames(directory):
    if filename.endswith(file_extensions):
        try:
            wb = xl.load_workbook(filename)
            print('Opened ' + filename)
            for sheet in wb.worksheets: 
                rows = sheet.max_row 
                columns = sheet.max_column
                for row in range(1,rows + 1): 
                    for column in range(1,columns + 1): 
                        if keyword in str(sheet.cell(row=row, column=column).value):
                            print('FOUND IN ' + filename)
                        else:
                            print("NOT FOUND")
        except:
                print('Failed to open ' + filename)

但是,openpyxl模块不支持.xls格式,因此我需要重写脚本以使用xlrd代替。

我尝试了以下操作:

for filename in filenames(directory):
    if filename.endswith(file_extensions):
        try:
            wb = xlrd.open_workbook(filename)
            print('Opened ' + filename)
            for sheet in wb.sheets(): 
                rows = sheet.nrows
                columns = sheet.ncols
                for row in range(1,rows + 1):
                    for column in range(1,column +1):
                        if keyword in str(sheet.cell(row, column).value):
                            print('FOUND IN ' + filename)
                        else:
                            print("NOT FOUND")
        except:
                print('Failed to open ' + filename)

但是随后代码无法打开工作簿(每个文件被打印的是“ Opened ...”,然后是“ Failed ...”。)

我还尝试将if keyword行更改为str(sheet.cell_value(row,column)),但无济于事。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

更改

            for row in range(1,rows + 1):
                for column in range(1,column +1):

            for row in range(rows):  # rows + 1 will result in 'out of range'
                for column in range(columns):  # note 'columns'  not 'column'

并删除(或缩小)Mel指出的try块。