Jack Christopher
Jack Christopher

Reputation: 13

How to generate new excel file for each iteration after looping the data from the input excel file

workbook = xlsxwriter.Workbook('ClaimSummaryReport.xlsx')
worksheet = workbook.add_worksheet()

format_1 = workbook.add_format({'num_format':''})
format_2 = workbook.add_format({'num_format':''})

# set the width
worksheet.set_column(0,0,90)
worksheet.set_column('B:B',80,format_2)
# start from where
row = 0
col = 0

for x in output:
    worksheet.write(row,col,    x, format_1 )
    worksheet.write(row,col + 1,output[x],format_2)
    row+=1

workbook.close()

This code is only generating one excel file. After each looping, it will overwrite the previous data.

Upvotes: 0

Views: 211

Answers (1)

Hamza
Hamza

Reputation: 6025

You can just cram everything inside a for loop for a dirty fix:

# start from where
row = 0
col = 0
for idx, x in enumerate(output):

    workbook = xlsxwriter.Workbook(f'ClaimSummaryReport{idx}.xlsx')
    worksheet = workbook.add_worksheet()
    
    format_1 = workbook.add_format({'num_format':''})
    format_2 = workbook.add_format({'num_format':''})
    
    # set the width
    worksheet.set_column(0,0,90)
    worksheet.set_column('B:B',80,format_2)

    worksheet.write(row,col,    x, format_1 )
    worksheet.write(row,col + 1,output[x],format_2)
    row+=1
    
    workbook.close()

Upvotes: 1

Related Questions