我使用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,因为必须将数据框导出到现有文件。
答案 0 :(得分:0)
解决方案是使用openpyxl版本2.1.3或2.1.5。