【问题标题】:XLRD, check if one sheet doesn't exist else check for anotherXLRD,检查一张纸是否不存在,否则检查另一张
【发布时间】:2020-03-04 07:23:22
【问题描述】:

试图读取一系列 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。我做错了什么?

【问题讨论】:

  • 即使你编辑了你的原始帖子self.wb 会引发AttributeError: 'Workbook_Reading' object has no attribute 'wb',因为你的类没有 wb 属性。也就是说,如果你得到xlrd.bffh.XLRDError: No Sheet Named <'Purchase History'>,这不是实际代码
  • 另外,c:sample.xls 缺少反冲并且会首先引发 FileNotFoundError
  • 如何创建工作表名称列表,然后在 try/catch 块中使用 sheet_by_name() 函数对其进行迭代。
  • 抱歉,我正在非常快速地制作示例代码。它确实有一个 self.wb 和一个 C:\。我会编辑这些,但@Jabb 我会尝试这样做。

标签: python xlrd


【解决方案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

【讨论】:

  • 谢谢!我试试看。
【解决方案2】:

正如@Jabb 在他最初的评论中所建议的那样,正确的方法是尝试/除外。他的例子虽然有点 [不必要] 过于复杂,例如无需创建方法来设置可用工作表,您可以简单地使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2010-10-12
    • 2019-12-08
    相关资源
    最近更新 更多