简体   繁体   中英

Write a one column in existing excel file using openpyxl

I want to write the values of the list values only on column "F" of the existing excel file, for example:

values = [5, 7, 1]
wb = Workbook(write_only=True)
ws = wb.create_sheet()
items = [i for i in values] 
for item in items:
    ws.append([item])

wb.save('newfile.xlsx')
ID   Name View  #RightSwipe #LeftSwipe  
145  abc    5   2   1   
146  xyz    8   3   6   
147  pqr    3   4   3   

add one column in last that's name "Order"

Order
5
7
1

append adds new rows at the end of the file. You want to add data to existing rows. Simply iterate over the list and add the values in their respective rows, at the last column:

ws.cell(row=1, column=ws.max_column+1, value="Order")
for row_num, value in enumerate(values, start=2):
    ws.cell(row=row_num, column=ws.max_column, value=value)

You can also use the iter_rows to iterate the rows while zip ping the values:

for row, value in zip(ws.iter_rows(min_row=2, min_col=ws.max_column, max_col=ws.max_column), values):
    row[0].value = value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM