Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data to a new tab in the .xlsx file

My program generates a data_list using a while loop (the code for generating the data_list is not important, and I have attached the main code below). At the end of the loop, after the data_list is generated, I want to write this data_list to the test.xlsx file. However, for each new data_list to be saved in a new tab (that is, if I had 10 iterations in the loop, there would be 10 different tabs in the test.xlsx file).

At the moment, my code works in such a way that each new tab overwrites the previous one, that is, at the end of the loop, there is one tab in the test.xlsx file.

Tell me how to do it in such a way that each new generated data_list is written in a new tab.

start=0
finish=1
datas = response.json()


while finish < 11:
    data = datas[start:finish]

    data_list = []
    # some code for generating the data_list

    df = pd.DataFrame(data_list)
    writer = pd.ExcelWriter('test.xlsx')
    df.to_excel(writer, sheet_name=f'{finish}', index=False)
    writer._save()

    finish +=1
    start +=1
like image 792
Paul Avatar asked Feb 01 '26 07:02

Paul


1 Answers

Instead of saving each sheet use with to create the ExcelWriter

with pd.ExcelWriter('test.xlsx') as writer:
    while finish < 11:
        data = datas[start:finish]

        data_list = []

        df = pd.DataFrame(data_list)
        df.to_excel(writer, sheet_name=f'{finish}', index=False)

        finish += 1
        start += 1
like image 83
Guy Avatar answered Feb 03 '26 19:02

Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!