使用xlsxwriter合并每隔一个单元格

时间:2019-12-01 02:53:06

标签: python xlsxwriter

我希望将第二个单元格与xlsxwriter合并,如下所示。

enter image description here

我已经尝试过

import xlsxwriter, os, datetime as dt

# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('AARs.xlsx')
worksheet = workbook.add_worksheet()

# Create a format to use in the merged range.
merge_format = workbook.add_format({
    'align': 'center',
    'valign': 'vcenter'})

# Start and end dates of the trial to go into the spreadsheet.
start_date = dt.datetime(2019, 8, 6)
end_date = dt.datetime(2019, 12, 13)
trial_length = end_date -start_date

# Merge cells.
for days in range(trial_length.days):
    worksheet.merge_range(1, 1+days, 1, 2+days, 'Merged Range', merge_format)

workbook.close()

我已经在下面明确写出了for循环

worksheet.merge_range(1, 1, 1, 2, 'Merge Range', merge_format)
worksheet.merge_range(1, 3, 1, 4, 'Merge Range', merge_format)
worksheet.merge_range(1, 5, 1, 6, 'Merge Range', merge_format)
worksheet.merge_range(1, 7, 1, 8, 'Merge Range', merge_format)
worksheet.merge_range(1, 9, 1, 10, 'Merge Range', merge_format)
worksheet.merge_range(1, 11, 1, 12, 'Merge Range', merge_format)
worksheet.merge_range(1, 13, 1, 14, 'Merge Range', merge_format)
worksheet.merge_range(1, 15, 1, 16, 'Merge Range', merge_format)
worksheet.merge_range(1, 17, 1, 18, 'Merge Range', merge_format)
worksheet.merge_range(1, 19, 1, 20, 'Merge Range', merge_format)

我现在在编写正确的循环时遇到了麻烦。我已经尝试过类似的东西:

count_odd = 0
count_even = 0
for days in range(trial_length.days):
    if not days % 2:
        worksheet.merge_range(1, 1, 1, 2 + count_even, 'Merge Range', merge_format)
        count_even += 1
    else:
        worksheet.merge_range(1, 1 + count_odd, 1, 2 + count_even, 'Merge Range', merge_format)
        count_odd += 1

但是这似乎也不起作用。 我正在尝试合并第二个单元格。

1 个答案:

答案 0 :(得分:0)

想通了。

odd = 1
even = 2
for day in range(trial_length.days):
    worksheet.merge_range(1, odd, 1, even, 'Merge Range', merge_format)
    odd += 2
    even += 2

答案几乎太明显了。