0

I have been working through Hilpisch's "Python for Finance" and haven't had much trouble until I got to the chapter on writing to Excel. I am running Python 3.5 and using the OpenPyxl module

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])

This returns: ValueError: Cannot convert 10 to Excel

Is it an issue with using numpy? For example, the following code returns a similar error.

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

But replacing data[0, 0] with an integer or float raises no problem.

Seems like there should be an easy fix to this.

2 Answers 2

2

openpyxl operates only with "known" types (int, string etc) which it knows how to convert to Excel data types. Unfortunately data[0, 0] is not known type:

➜ 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'>

You have to convert numpy.int64 to int type:

>>> 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)
Sign up to request clarification or add additional context in comments.

Comments

0

Support for numpy types has been added to openpyxl 2.4 which you can install using pip install -U --pre openpyxl.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.