Python 3.5使用openpyxl编写numpy

我一直在努力通过Hilpisch的“Python for Finance”,并没有太多的麻烦,直到我写到Excel的章节。 我正在运行Python 3.5并使用OpenPyxl模块

import openpyxl as oxl import numpy as np wb = oxl.Workbook() ws = wb.create_sheet(index = 0, title = 'oxl_sheet') data = np.arange(1, 65).reshape((8, 8)) for c in range(1, data.shape[0]): for r in range(1, data.shape[1]): ws.cell(row=r, column=c, value=data[c, r]) 

这将返回: ValueError: Cannot convert 10 to Excel

这是使用numpy的问题吗? 例如,下面的代码返回一个类似的错误。

 ws.cell(row=1, column=1, value=data[0,0]) 

但用整数或浮点数replacedata[0, 0]没有问题。

似乎应该有一个简单的解决这个问题。

openpyxl只能使用知道如何转换为Excel数据types的“已知”types(int,string等)。 不幸的是data[0, 0]是不知道的types:

 ➜ python Python 2.7.10 (default, Oct 14 2015, 16:09:02) [GCC 5.2.1 20151010] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> data = np.arange(1, 65).reshape((8, 8)) >>> type(data[0, 1]) <type 'numpy.int64'> 

您必须将numpy.int64转换为inttypes:

 >>> for c in range(1, data.shape[0]): ... for r in range(1, data.shape[1]): ... ws.cell(row = r, column = c).value = data[c, r].astype(int) 

对npypytypes的支持已经添加到了openpyxl 2.4中,您可以使用pip install -U --pre openpyxlpip install -U --pre openpyxl