1

I have a script which creates an excel workbook with two worksheets, the script formats cells, etc. in sheet1 however I also want to do the same formatting in sheet2. Is there an easy way to do the formatting to both sheets at the same time instead of making a full copy of what is done for sheet1 and doing for sheet2 also. Below is some of the code i have and want to do for both sheets

workbook = xlsxwriter.Workbook(outFileXLSX)                           
worksheet1 = workbook.add_worksheet('Results 1') 
worksheet2 = workbook.add_worksheet('Results 2')     
sheet1 = worksheet1    
sheet2 = worksheet2 

sheet1.merge_range('A1:A4', '', format_header)                         
sheet1.merge_range('B1:B4', 'Merged Range', format_header)

The two lines above i need to do also in sheet2 Any help or advise would be great

2
  • for s in [sheet1,sheet2]: Commented May 31, 2017 at 21:23
  • WNG - new to python can you elaborate further how to implement? Commented May 31, 2017 at 21:25

1 Answer 1

1

Turn the repeated steps into a function and pass in the parameters, so something like:

def do_stuff(workbook, names):
    '''
    Call this function with the workbook reference and a sequence of sheet names
    '''
    for sheet in names:  # this will do the following for each name in the sequence
        worksheet = workbook.add_worksheet(sheet)
        worksheet.merge_range('A1:A4', '', format_header)                         
        worksheet.merge_range('B1:B4', 'Merged Range', format_header)
        # any other stuff you want to do to each worksheet


# Here is your main block now...
workbook = xlsxwriter.Workbook(outFileXLSX)                           
do_stuff(workbook, ['Results 1', 'Results 2'])  
Sign up to request clarification or add additional context in comments.

1 Comment

Docstring needs to be indented.

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.