openpyxl+load_workbook+AttributeError: 'NoneTy

2019-05-29 23:01发布

问题:

When I use openpyxl to load the Excel file( .xlsx), this error displays (the last the link is the sample Excel file):

from openpyxl import * wb = load_workbook("D:/develop/workspace/exman/test sample/510001653.xlsx")

Traceback (most recent call last):

File "", line 1, in

File "C:\Python34\lib\site-packages\openpyxl-2.5.0-py3.4.egg\openpyxl\reader\ xcel.py", line 161, in load_workbook

parser.parse()

File "C:\Python34\lib\site-packages\openpyxl-2.5.0-py3.4.egg\openpyxl\packagi g\workbook.py", line 42, in parse

if package.properties.date1904:

AttributeError: 'NoneType' object has no attribute 'date1904'

sample excel file download

回答1:

I debug the python file ,and find that the workbookPr = None , cause the package.properties to None( properties = Alias(workbookPr). So I change the code of workbookParser.parser() like follow, the error is solved.

class WorkbookParser:

def __init__(self, archive):
    self.archive = archive
    self.wb = Workbook()
    self.sheets = []
    self.rels = get_dependents(self.archive, ARC_WORKBOOK_RELS)


def parse(self):
    src = self.archive.read(ARC_WORKBOOK)
    node = fromstring(src)
    package = WorkbookPackage.from_tree(node)

    if package.properties is not None: #add this line 
        if package.properties.date1904:
            wb.excel_base_date = CALENDAR_MAC_1904
        self.wb.code_name = package.properties.codeName
   self.wb.active = package.active

..........



回答2:

This bug was fixed in newer versions (I checked 2.4.8 and its fixed. 2.4.0 still had it)

pip install --upgrade openpyxl