我使用pandas库编写了一个程序。我正在尝试写入excel文件,并编写了以下代码:
writer = pd.ExcelWriter(DIR_PATH + 'output.xlsx', engine='xlsxwriter')
styled.to_excel(writer, sheet_name='Sheet1', index=False)
styled2.to_excel(writer, sheet_name='Sheet2', index=False)
print(styled2)
styled3.to_excel(writer, sheet_name='Sheet3', index=False)
print(styled3)
writer.save()
writer.close()
excel.Application.Quit()
################ setting column width to fit data ##################
wb = excel.Workbooks.Open(DIR_PATH + 'output.xlsx')
ws1 = wb.Worksheets("Sheet1")
wb.Save()
ws2 = wb.Worksheets("Sheet2")
wb.Save()
ws3 = wb.Worksheets("Sheet3")
wb.Save()
ws1.Columns.AutoFit()
ws2.Columns.AutoFit()
ws3.Columns.AutoFit()
wb.Save()
wb.close()
excel.Application.Quit()
我得到了错误:
Traceback (most recent call last):
File "K:/test_results.efrat.py", line 151, in <module>
styled.to_excel(writer, sheet_name='Sheet1', index=False)
File "K:\venv\lib\site-packages\pandas\io\formats\style.py", line 175, in to_excel
engine=engine)
File "K:\venv\lib\site-packages\pandas\io\formats\excel.py", line 652, in write
freeze_panes=freeze_panes)
File "K:\venv\lib\site-packages\pandas\io\excel.py", line 1750, in write_cells
for cell in cells:
File "K:\venv\lib\site-packages\pandas\io\formats\excel.py", line 617, in get_formatted_cells
self._format_body()):
File "K:\venv\lib\site-packages\pandas\io\formats\excel.py", line 529, in _format_regular_rows
for cell in self._generate_body(coloffset):
File "K:\venv\lib\site-packages\pandas\io\formats\excel.py", line 601, in _generate_body
styles = self.styler._compute().ctx
File "K:\venv\lib\site-packages\pandas\io\formats\style.py", line 514, in _compute
r = func(self)(*args, **kwargs)
File "K:\venv\lib\site-packages\pandas\io\formats\style.py", line 604, in _applymap
result = self.data.loc[subset].applymap(func)
File "K:\venv\lib\site-packages\pandas\core\indexing.py", line 1472, in __getitem__
return self._getitem_tuple(key)
File "K:\venv\lib\site-packages\pandas\core\indexing.py", line 890, in _getitem_tuple
retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
File "K:\venv\lib\site-packages\pandas\core\indexing.py", line 1901, in _getitem_axis
return self._getitem_iterable(key, axis=axis)
File "K:\venv\lib\site-packages\pandas\core\indexing.py", line 1143, in _getitem_iterable
self._validate_read_indexer(key, indexer, axis)
File "K:\venv\lib\site-packages\pandas\core\indexing.py", line 1206, in _validate_read_indexer
key=key, axis=self.obj._get_axis_name(axis)))
KeyError: "None of [['Failed/Passed']] are in the [columns]"
Exception ignored in: <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x00000000176730F0>>
Traceback (most recent call last):
File "K:\venv\lib\site-packages\xlsxwriter\workbook.py", line 154, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.
但是我在代码末尾使用了wb.close()
,所以我不明白为什么会出现这个异常。有人知道问题出在哪里吗,我该如何解决呢?谢谢。