user16646545
user16646545

Reputation:

Assign name to excel sheet from variable in list

I have account names that are saved in a python list, let's say "account a", "account b", "account c" and so on. This list has been saved in a Pandas dataframe.

I'd like to have an excel file created for each of those accounts, but I want the file to have the name of the account that it represents.

My initial thought was to create a for loop and use xlsxwriter, something like this....

    with pd.ExcelWriter(workbook, engine = 'xlsxwriter') as writer: 
        account_list = ['account a', 'account b', 'account c']



for account in account_list: 

        workbook = xlsxwriter.Workbook([account_list])
        worksheet = workbook.add_worksheet([account_list])

        account_list.to_excel(writer, sheet_name = f'[worksheet]')

You can probably guess that I get an error, saying "expected string or bytes-like object."

Any thoughts on how to make this work?

Upvotes: 0

Views: 1751

Answers (1)

A. Mello
A. Mello

Reputation: 51

Use the variable choosed in for loop:

import xlsxwriter

account_list = ['account a', 'account b', 'account c']

for account in account_list:

    workbook = xlsxwriter.Workbook( account + '.xlsx')  # the file name is given by account
    worksheet = workbook.add_worksheet(account) # if 'account' ommited, the sheet is named as 'sheet1'

    worksheet.write('A1', account)

    workbook.close()

Upvotes: 1

Related Questions