我使用 pandas 0.15
和 openpyxl 2.2.0
作为编写器引擎,但 pandas 0.16
也出现同样的问题 .
我需要将pandas数据帧导出到 .xlsx
文件 . 数据框非常简单 - 类似于:
col_A col_B col_C
0 1 100 AB
1 2 200 AC
2 3 300 AD
我可以导出数据帧的内容(即没有索引标签和列名称):
df.to_excel(path_to_xlsx_file, sheet_name, header=False, index=False)
但是,如果我包含索引标签或列名称(或两者),我会得到一个TypeError . 这个:
df.to_excel(path_to_xlsx_file, sheet_name, header=False, index=True)
或这个:
df.to_excel(path_to_xlsx_file, sheet_name, header=True, index=False)
导致这个:
Traceback (most recent call last):
File "<ipython-input-11-a60810c2c9c2>", line 1, in <module>
runfile('F:/mine/python/pandas_tests.py', wdir='F:/mine/python')
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
execfile(filename, namespace)
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 66, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "F:/mine/python/pandas_tests.py", line 25, in <module>
df.to_excel(path_to_xlsx_file, sheet_name, header=True, index=False)
File "C:\Python27\lib\site-packages\pandas\util\decorators.py", line 88, in wrapper
return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1260, in to_excel
startrow=startrow, startcol=startcol)
File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 705, in write_cells
xcell.style = xcell.style.copy(**style_kwargs)
File "C:\Python27\lib\site-packages\openpyxl-2.2.0-py2.7.egg\openpyxl\styles\styleable.py", line 107, in style
protection=self.protection
File "C:\Python27\lib\site-packages\openpyxl-2.2.0-py2.7.egg\openpyxl\styles\__init__.py", line 42, in __init__
self._font = font
File "C:\Python27\lib\site-packages\openpyxl-2.2.0-py2.7.egg\openpyxl\descriptors\base.py", line 35, in __set__
raise TypeError('expected ' + str(self.expected_type))
TypeError: expected <class 'openpyxl.styles.fonts.Font'>
我不能使用xlsxwriter,因为必须将数据框导出到现有文件 .
1 回答
解决方案是使用openpyxl版本2.1.3或2.1.5 .