Joseph
Joseph

Reputation: 351

Writing to one column using openpyxl

I want to write the values of the list values only on column A of the new workbook, for example:

 a1 = 1
 a2 = 2
 a3 = 3

etc. etc. but right now I get this:

a1 = 1   b1 = 2  c1= 3 d1= 4
a1 = 1   b1 = 2  c1= 3 d1= 4
a1 = 1   b1 = 2  c1= 3 d1= 4

My code:

# create new workbook and worksheet

values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
wb = Workbook(write_only = True)
ws = wb.create_sheet()

for row in range(0, len(values)):
    ws.append([i for i in values])

wb.save('newfile.xlsx')

this code above fills all the cells in range A1:A15 to O1:O15 I only want to fill the values in column A1:A15

Upvotes: 1

Views: 9972

Answers (2)

Bramhadev Bachute
Bramhadev Bachute

Reputation: 1

You need to create nested list to append the values in column, refer below code.

from openpyxl import Workbook

values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

wb = Workbook() ws = wb.create_sheet()

newlist = [[i] for i in values]

print(newlist)

for x in newlist: ws.append(x)

wb.save('newfile.xlsx')

Upvotes: 0

user447688
user447688

Reputation:

Not yet tested, but I would think

Tested-- you have a syntax error also; substitute 'row' for 'i'. But the following works.

for row in range(0, len(values)):
    ws.append([row])

Upvotes: 2

Related Questions