简体   繁体   中英

How to append a list to an existing excel workbook (same sheet) in python

I am trying to append a list to an existing sheet (appending the list as a row) using two different methods. The first one runs fine but there is no change in the sheet. the second one appends the list but by criating a new sheet (which is no not my goal). The problem with the existing sheet is that there is data from column A5 in ahead,and I want to append the list filling the blanks cells (A1 to A4). In other words I do not want to erase the existing data or move it by including a nwe row. I have tried out the following methods:

    #the existing sheet looks like that:
    A1 A2 A3 A4 A5 A6......
                5  6 ......
                2  7 ......
                .  . ......
                .  . ......
    import pandas as pd
    import numpy as np
    import openpyxl

    #solution 1
    lista=[1,2,3,4]
    wb= openpyxl.load_workbook('teste.xlsx')
    sheetname = wb['Hoja1']
    sheetname.cell(row=3,column=1).value=str(lista)

    #solution 2  
    with pd.ExcelWriter('teste.xlsx', mode='a') as writer:
            pd.DataFrame(lista).to_excel(writer,  header=False, index=False, startrow=3, startcol=1, 
            sheet_name="Hoja1")

Can you help me out?

You can use pandas.to_excel and pandas.read_excel ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html and https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html ), the data you can add to the dataframe like columns, not rows:

# first read your data set
df = pd.read_excel('teste.xlsx', sheet_name='Hoja1')
# then add your columns
df['A1'] = 1 # you write only one value but I guess you have more
...
# and save
df.to_excel("teste.xlsx", sheet_name='Hoja1')

Edit (18.5.):

If you insist on appending rows (I do not know how your data is generated and if you can maybe feed the dataFrame directly with indexing), I'd recommend splitting your original data (alternatively load just the second part), create new dataFrame from your data row by row and then concat them, ie:

# take the second part after A5 column which you do not want to change
df2 = df.loc[:,'A5':]

# take the first part and use only column names
df1 = df.loc[:,:'A4'].dropna()
# append your data, here 2 rows
df1 = df1.append(pd.DataFrame([[5, 6, 3, 2], [7, 8, 1, 5]], columns=df1.columns))

# concat
df3 = pd.concat([df1, df2], axis=1)
# and save
df3.to_excel("teste.xlsx", sheet_name='Hoja1')

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