0

I am trying to write data to an Excel file, during a for loop. But what I am getting is a single line containing the last data received by the loop.

I have tried a couple of different methods but came short.. 2 tries are list below

Any Ideas ?

def write_excel(x):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    worksheet = workbook.add_worksheet()

    df = pd.DataFrame(
        {'ID':[x],
         'mail_one':[Email],
         'second_mail':[second_mail],
         'Num':[Num],
         'date':[Date]})

    row_num = 0
    for key, value in df.items():
        worksheet.write(0, row_num, key)
        worksheet.write_row(1, row_num, value)
        row_num += 1

    workbook.close()

    #df = pd.DataFrame(
    #    {'ID':[x],
    #     'mail_one':[Email],
    #     'second_mail':[second_mail],
    #     'Num':[Num],
    #     'date':[Date]})

    # writer = ExcelWriter('ID_Num.xlsx')
    # df.to_excel(writer,'ID_Num',index=False)

    # writer.save()


if __name__ == "__main__":
    for x in List:
        my_dic = {}
        my_dict["ID"] = x
        my_dict["mail_one"] = Email
        my_dict["second_mail"] = second_mail
        my_dict["Num"] = str(Num)
        my_dict["date"] = Date
        print(my_dict)
        write_excel(x)

4
  • 2nd_mail isnt a valid variable name. You sure its not erroring on that? Share full error stack Commented Oct 19, 2020 at 16:12
  • @User5 Actually it is only for example sake, none the less I fixed it in the code. Commented Oct 19, 2020 at 17:06
  • Ideas: Pandas and xlsxwriter: how to create a new sheet without exporting a dataframe?, docs - Working with Python Pandas and XlsxWriter Commented Oct 19, 2020 at 17:13
  • @wwii As far as I see I am already doing this in my code, but it doesnt seem to work when looping. it is only writing the last data received, not going to the next line, while when submitting the whole data as one, it does, so how do I make it loop ?... Commented Oct 20, 2020 at 6:39

1 Answer 1

1

I don't have xlsxwriter so I cannot test. The documentation says that it cannot modify an existing file so I suspect that every iteration of for x in List: you are over-writing your file (workbook = xlsxwriter.Workbook('ID_Num.xlsx')).

You can make multiple files with these changes:

def write_excel(x,i):
    workbook = xlsxwriter.Workbook(f'ID_Num{i}.xlsx')
    ...
# and
for i,x in enumerate(List):
    ...
    write_excel(x,i)

Or you could accumulate multiple dictionaries and pass all of them to your function

data = []
for x in List:
    my_dic = {}
    ...
    data.append(my_dic)
write_excel(data)

Changing the function to iterate over those dicts; making a new sheet for each one

def write_excel(data):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    for sht in data:
        worksheet = workbook.add_worksheet()
        df = pd.DataFrame(...

        row_num = 0
        for key, value in df.items():
            worksheet.write(...
            worksheet.write_row(...
            row_num += 1

    workbook.close()
Sign up to request clarification or add additional context in comments.

1 Comment

Beautifully answered! I went with the 'accumulate multiple dictionaries' and it worked like a charm. I placed the name of the dict after the variable dict_data = account_details I was actually surprised that it worked (one variable = another), but it did (-:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.