gil*_*iev 5 python excel xlsx python-2.7 openpyxl
我有一个 .xlsx 文件,其中包含 2 个工作表。第一个包含常规数据(没什么花哨的),而第二个包含数据透视表。我只需要第一个工作表中的数据,我想忽略第二个工作表,但数据透视表会引发错误:TypeError: expected <type 'basestring'>何时openpyxl.load_workbook调用。
错误出现在:openpyxl/reader/excel.py,行: 中 pivot_caches = parser.pivot_caches。
我尝试过openpyxl版本2.6.4和2.5.1. 我正在使用Python 2.7。
删除第二个工作表后,错误消失,并且可以正确读取第一个工作表中的数据。但是,这些文件是由用户上传的,虽然我不需要数据透视表,但如果可能的话,我想避免强迫用户删除不必要的工作表。
示例代码:
from io import BytesIO
import openpyxl
pivot = '~/Downloads/file_with_pivot_tables.xlsx'
with open(pivot) as fin:
content = BytesIO(fin.read())
wb = openpyxl.load_workbook(content) # this line fails
ws = wb.get_sheet_by_name('Sheet1')
Run Code Online (Sandbox Code Playgroud)
整个错误跟踪:
File "/Users/gi/lib/openpyxl/reader/excel.py", line 224, in load_workbook
pivot_caches = parser.pivot_caches
File "/Users/gi/lib/openpyxl/packaging/workbook.py", line 125, in pivot_caches
cache = get_rel(self.archive, self.rels, id=c.id, cls=CacheDefinition)
File "/Users/gi/lib/openpyxl/packaging/relationship.py", line 162, in get_rel
obj.deps = get_dependents(archive, rels_path)
File "/Users/gi/lib/openpyxl/packaging/relationship.py", line 130, in get_dependents
rels = RelationshipList.from_tree(node)
File "/Users/gi/lib/openpyxl/descriptors/serialisable.py", line 84, in from_tree
obj = desc.expected_type.from_tree(el)
File "/Users/gi/lib/openpyxl/descriptors/serialisable.py", line 100, in from_tree
return cls(**attrib)
File "/Users/gi/lib/openpyxl/packaging/relationship.py", line 50, in __init__
self.Target = Target
File "/Users/gi/lib/openpyxl/descriptors/base.py", line 44, in __set__
raise TypeError('expected ' + str(self.expected_type))
TypeError: expected <type 'basestring'>
Run Code Online (Sandbox Code Playgroud)
小智 0
您可以指定要操作的工作表:
wb = openpyxl.load_workbook('H:\\myfile.xlsx')
ws = wb['sheet1']
ws['E1'] = 'The sky is gray.'
wb.save('H:\\myfile.xlsx')
wb.close()
Run Code Online (Sandbox Code Playgroud)
如果您需要先检查它们,您还可以获得所有工作表名称的列表:
print(wb.sheetnames)
Run Code Online (Sandbox Code Playgroud)