XLRD,检查一张纸是否不存在,检查另一张纸

时间:2020-03-04 07:23:22

标签: python xlrd

尝试读取一系列xls文件。它们的格式不统一。有时床单存在,有时不存在。有时他们有一个名字,有时又有一个名字。这是一个不完美的世界。

我尝试检查工作表名称的某些代码:

import xlrd

wb=xlrd.open_workbook(r'C:\sample.xls')

class Workbook_Reading:

    def __init__(self, wb):
        self.wb = wb
        self.history = None

    def purch_hist(self):
        if self.wb.sheet_loaded('Purchase History') is True:
            purchase_history = wb.sheet_by_name('Purchase History')
            self.history = purchase_history
        elif self.wb.sheet_loaded('Previous Purchases') is True:
            purchase_history = wb.sheet_by_name('Previous Purchases')
            self.history = purchase_history
        else:
            pass

我不断收到错误消息:xlrd.bffh.XLRDError: No Sheet Named <'Purchase History'>。我正在测试一个wb,我知道它没有第一个条件(“购买历史记录”表),但具有另一个条件(“先前的购买表”)。我做错了什么?

2 个答案:

答案 0 :(得分:1)

这可能有帮助

import xlrd

class Workbook_Reading:

    def __init__(self, wb):
        self.history = None
        self.desiredSheetNames = ['Purchase History', 'Previous Purchases']
        self.availableSheetNames = []
        self.wb = xlrd.open_workbook(r'C:\\sample.xls')
        self.set_available_sheets()

    def set_available_sheets(self):
        for sheetName in self.desiredSheetNames:
            try:
                sheet = self.wb.sheet_by_name(sheetName)
                self.availableSheetNames.append(sheetName)
            except:
                pass

    def purch_hist(self):
        if 'Purchase History' in self.availableSheetNames:
            purchase_history = wb.sheet_by_name('Purchase History')
            self.history = purchase_history
        elif 'Previous Purchases') in self.availableSheetNames:
            purchase_history = wb.sheet_by_name('Previous Purchases')
            self.history = purchase_history
        else:
            pass

答案 1 :(得分:0)

正如@Jabb在其初始评论中建议的那样,正确的方法是try / except。不过,他的示例有点[不必要]过于复杂,例如无需创建设置可用工作表的方法,只需使用book.sheet_names()都一样(检查是否存在具有给定名称的工作表)。但是正如我所说,甚至不必检查是否使用if / elif / else块,只需使用try / except。

import xlrd

file_name = r'some_path\some_file.xls' # replace with your file

class Workbook_Reader:
    def __init__(self, wb, lookup_sheets=('Purchase History', 'Previous Purchases')):
        self.wb = xlrd.open_workbook(wb)
        self.lookup_sheets = lookup_sheets

    @property
    def purchase_history(self): # this property will return the respective sheet or None
        for sheet_name in self.lookup_sheets:
            try:
                return self.wb.sheet_by_name(sheet_name)
            except xlrd.biffh.XLRDError:
                pass

foo = Workbook_Reader(file_name)
for row in foo.purchase_history.get_rows():
    for cl in row:
        print(cl.value)

请注意,要遍历lookup_sheets first seen wins

相关问题