1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import openpyxl import xlrd import os
class Sheet: def cell_value(self, row, col): pass
class XlsxSheet(Sheet): def __init__(self, sheet): self.sheet = sheet
def cell_value(self, row, col): return self.sheet.cell(row=row+1, column=col+1).value
class XlsSheet(Sheet): def __init__(self, sheet): self.sheet = sheet
def cell_value(self, row, col): return self.sheet.cell_value(row, col)
class _Workbook: def sheet_by_index(self, index): pass
class XlsxFile(_Workbook): def __init__(self, path): self.workbook = openpyxl.load_workbook(path)
def sheet_by_index(self, index): sheet = self.workbook[self.workbook.sheetnames[index]] return XlsxSheet(sheet)
class XlsFile(_Workbook): def __init__(self, path): self.workbook = xlrd.open_workbook(path)
def sheet_by_index(self, index): sheet = self.workbook.sheet_by_index(index) return XlsSheet(sheet)
class Workbook: def __init__(self, path): filedir, filename = os.path.split(path) _, extname = os.path.splitext(filename) if extname == ".xlsx": self.impl = XlsxFile(path) elif extname == ".xls": self.impl = XlsFile(path) else: raise IOError("未知的文件类型")
def sheet_by_index(self, index): return self.impl.sheet_by_index(index)
|