Python: How to write a complex number to excel using xlwt?

女生的网名这么多〃 提交于 2019-12-22 18:32:15

问题


I am trying to write a Python list to an excel file using xlwt library.

import xlwt
from tempfile import TemporaryFile
book = xlwt.Workbook()
sheet1 = book.add_sheet('sheet1')
for i in range(len(newdata)):
    for j in range(len(newdata[i])):
        sheet1.write(i,j,newdata[i][j])
name = "my_file.xls"
book.save(name)
book.save(TemporaryFile())

It work for common variable types (e.g. int, float, string) but when I try to write a complex number to the excel file, I get the following error:

Exception: Unexpected data type <type 'complex'>

As I understand write does not support complex numbers. Does anyone know how to write complex values to excel?! P.S. I don't want to write the data to a CSV file. It needs to be a .xls file.


回答1:


You can convert the complex number into a string using sheet1.write(i,j,str(newdata[i][j])). This will help you get out of the traceback.



来源:https://stackoverflow.com/questions/19109281/python-how-to-write-a-complex-number-to-excel-using-xlwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!