我有一个脚本,它创建了一个包含两个工作表的excel工作簿,脚本在sheet1
中格式化单元格等,但我也希望在sheet2
中执行相同的格式设置。是否有一种简单的方法可以同时对两个工作表进行格式化,而不是完整复制sheet1
并为sheet2
执行的操作。
以下是我对这两张表所要做的一些代码
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)
我需要在sheet2
中执行以上两行
任何帮助或建议都会很棒
答案 0 :(得分:1)
将重复的步骤转换为函数并传入参数,如下所示:
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'])