XLRD,检查一个 sheet 是否不存在,否则检查另一个

XLRD, check if one sheet doesn't exist else check for another

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

我尝试检查 sheet 名称的一些代码:

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 我知道具体没有第一个条件(购买历史 sheet),但有另一个(以前的购买 sheet)。我做错了什么?

这可能有帮助

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

正如@Jabb 在他最初的评论中所建议的那样,正确的做法是 try/except。他的例子虽然有点[不必要]过于复杂,例如无需创建方法来设置可用的 sheets,您可以简单地使用 book.sheet_names()(检查是否存在具有给定名称的 sheet)。但正如我所说,甚至没有必要使用 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