I'm trying to append cell value using openpyxl, by appending the value directly.
this works:
wb1=load_workbook('test.xlsx')
ws1=wb1.active
testlist=('two','three','four','five')
for i in testlist:
ws1['A1'].value = ws1['A1'].value (' ') i
print(ws1['A1'].value)
A1 has a value of "one", after the loop runs it has "one two three four five"
But is it possible to use the append method directly on the cell value?
for i in testlist:
ws1.append['A1'].value = i
however this throws an error "TypeError: 'method' object does not support item assignment"
CodePudding user response:
You will need to move the tuple into a string and can add it to cell A1
like this.
wb1=Workbook()
ws1=wb1.active
testlist=('one','two','three','four','five')
myString = ' '.join(map(str, testlist))
myString.strip()
ws1['A1'].value = myString
wb1.save('test1.xlsx')
CodePudding user response:
The error "method' object is not subscriptable" means that, you are treating an object as python dict
or dict
like object which the object isn't. Because the append
method returns None.
As per documentation of openpyxl, You can worksheet.append via:
- A list: all values are added in order, starting from the first column. which is your case. simply doing the following should work:
wb1=Workbook()
ws1=wb1.active
testlist=('one','two','three','four','five')
# append each element side by side in a single row
ws1.append(testlist)
# To append each element vertical direction in new row you can un-comment next 2 lines.
#for entry in testlist:
# ws1.append([entry])
wb1.save('test.xlsx')
- A dict: values are assigned to the columns indicated by the keys (numbers or letters). This might help if you are targeting a specific column.
Or
To have more control simply use worksheet.cell.