Search code examples
pythonexcellistadditionopenpyxl

I want to add list of values to a single excel cell using Openpyxl but it returning following error


The error I am getting ValueError: Cannot convert [0, 8.017587061595629, 6.476105944459858, 14.247103467749781, 18.55773218714581, 32.68428298499151, 19.87675167486509] to Excel

I want to add the data in ls to ws1.cell (1,1), but when I am trying to add using above code it returning error. I can recall with same method I was able to add list of values to single cell when my code was running on python 2.7 and older version of openpyxl.

here is my code

from openpyxl import load_workbook, Workbook
wb1 = Workbook()
ws1 = wb1.create_sheet(index=None, title="2020")
ls=[0,8.017587061595629,6.476105944459858,14.247103467749781,18.55773218714581,32.68428298499151,19.87675167486509]
ws1.cell(1,1).value=ls```


**In more details error is:**

ValueError                                Traceback (most recent call last)
Cell In[1025], line 2
      1 ls=[0,8.017587061595629,6.476105944459858,14.247103467749781,18.55773218714581,32.68428298499151,19.87675167486509]
----> 2 ws1.cell(1,1).value=ls

File ~\AppData\Local\anaconda3\lib\site-packages\openpyxl\cell\cell.py:215, in Cell.value(self, value)
    212 @value.setter
    213 def value(self, value):
    214     """Set the value and infer type and display options."""
--> 215     self._bind_value(value)

File ~\AppData\Local\anaconda3\lib\site-packages\openpyxl\cell\cell.py:184, in Cell._bind_value(self, value)
    181     dt = get_type(t, value)
    183 if dt is None and value is not None:
--> 184     raise ValueError("Cannot convert {0!r} to Excel".format(value))
    186 if dt:
    187     self.data_type = dt

ValueError: Cannot convert [0, 8.017587061595629, 6.476105944459858, 14.247103467749781, 18.55773218714581, 32.68428298499151, 19.87675167486509] to Excel

Solution

  • The answer is still the same, you cannot write a list to a single cell. You can append a list like the answer from @traceurSaimn. That will add the list to the next row after the last used from column A. But this doesn't appear to be what you want from the description.
    If you want to write all the list to one cell then it needs to be a string.

    from openpyxl import load_workbook, Workbook
    wb1 = Workbook()
    ws1 = wb1.create_sheet(index=None, title="2020")
    ls=[0,8.017587061595629,6.476105944459858,14.247103467749781,18.55773218714581,32.68428298499151,19.87675167486509]
    s = ','.join(str(x) for x in ls)
    ws1.cell(1,1).value=s
    
    wb1.save('foo.xlsx')
    

    If you do want to add the list so each element is entered to a separate cell not appended as the last row, but rather specify the cells the list elements are entered, you'll need to loop the list and write each value by specifying the coordinate thru incrementing the column.